PHP pre-defined interface-ArrayAccess, php pre-defined arrayaccess

Source: Internet
Author: User

PHP pre-defined interface-ArrayAccess, php pre-defined arrayaccess

I recently went home for the Chinese New Year, and my blog has not been updated. I feel that I have learned a lot and missed many learning opportunities, just like what I often say during the Spring Festival: I missed hundreds of millions. This blog tells you about ArrayAccess, a heavyweight character commonly used in PHP pre-defined interfaces. You may ask why there are six basic and most commonly used predefined interfaces. From the perspective of daily usage: This is frequently used, especially in frameworks, such as Laravel and Slim. It is very classic and admirable. Technically speaking: To tell the truth, I rarely use other products! I only know the simple usage and have a simple understanding of him. I dare not mislead everyone here, haha! The content I want to write today is not always correct. please correct me if it is not correct.

ArrayAccess

Let's talk about ArrayAccess first! ArrayAccess is used to make your object accessible like an array. It should be said that ArrayAccess started in PHP5. PHP5 has added many new features, and of course it has also increased the class overload. PHP5 has added a series of interfaces, these interfaces and implementation classes are collectively referred to as SPL.

The ArrayAccess interface defines four methods that must be implemented:

1 {2 abstract public offsetExists ($ offset) // check whether the offset position exists. 3 abstract public offsetGet ($ offset) // obtain the value of an offset position 4 abstract public void offsetSet ($ offset, $ value) // set the value of an offset position 5 abstract public void offsetUnset ($ offset) // reset the value of one offset position to 6}

Therefore, to use the ArrayAccess interface, we need to implement the corresponding methods. These methods are not written at will. Let's take a look at the ArrayAccess prototype:

 1 /** 2  * Interface to provide accessing objects as arrays. 3  * @link http://php.net/manual/en/class.arrayaccess.php 4  */ 5 interface ArrayAccess { 6  7     /** 8      * (PHP 5 &gt;= 5.0.0)<br/> 9      * Whether a offset exists10      * @link http://php.net/manual/en/arrayaccess.offsetexists.php11      * @param mixed $offset <p>12      * An offset to check for.13      * </p>14      * @return boolean true on success or false on failure.15      * </p>16      * <p>17      * The return value will be casted to boolean if non-boolean was returned.18      */19     public function offsetExists($offset);20 21     /**22      * (PHP 5 &gt;= 5.0.0)<br/>23      * Offset to retrieve24      * @link http://php.net/manual/en/arrayaccess.offsetget.php25      * @param mixed $offset <p>26      * The offset to retrieve.27      * </p>28      * @return mixed Can return all value types.29      */30     public function offsetGet($offset);31 32     /**33      * (PHP 5 &gt;= 5.0.0)<br/>34      * Offset to set35      * @link http://php.net/manual/en/arrayaccess.offsetset.php36      * @param mixed $offset <p>37      * The offset to assign the value to.38      * </p>39      * @param mixed $value <p>40      * The value to set.41      * </p>42      * @return void43      */44     public function offsetSet($offset, $value);45 46     /**47      * (PHP 5 &gt;= 5.0.0)<br/>48      * Offset to unset49      * @link http://php.net/manual/en/arrayaccess.offsetunset.php50      * @param mixed $offset <p>51      * The offset to unset.52      * </p>53      * @return void54      */55     public function offsetUnset($offset);56 }

Below we can write an example, which is very simple:

1 <? Php 2 class Test implements ArrayAccess 3 {4 private $ testData; 5 6 public function offsetExists ($ key) 7 {8 return isset ($ this-> testData [$ key]); 9} 10 11 public function offsetSet ($ key, $ value) 12 {13 $ this-> testData [$ key] = $ value; 14} 15 16 public function offsetGet ($ key) 17 {18 return $ this-> testData [$ key]; 19} 20 21 public function offsetUnset ($ key) 22 {23 unset ($ this-> testData [$ key]); 24} 25} 26 2 7 $ obj = new Test (); 28 29 // automatically call the offsetSet Method 30 $ obj ['data'] = 'data '; 31 32 // automatically call offsetExists33 if (isset ($ obj ['data']) {34 echo 'has setting! '; 35} 36 // automatically call offsetGet37 var_dump ($ obj ['data']); 38 39 // automatically call offsetUnset40 unset ($ obj ['data']); 41 var_dump ($ test ['data']); 42 43 // output: 44 // has setting! 45 // data 46 // null

Well, next we will use the Slim framework in practice. It is very important to use it in Slim, and it is also very good to use the container. The container inherits from Pimple \ Container. Speaking of this, pimple is a popular ioc container in the php community. The container class in pimple uses dependency injection to achieve low coupling between programs, you can use composer to add require "pimple/pimple": "1. * "when adding Pimple to the dependent class library, Pimple still needs to be viewed more. Just one file can be registered for various attributes, methods, objects, and closures throughout the life cycle of the program, however, pimple only implements the concept of a container. There are many dependency injection, automatic creation, association, and other functions that need to be viewed by Laravel.

In Slim, it uses the container class to load configuration files in sequence and access them like an array, including displayErrorDetails, renderer, logger, httpVersion, responseChunkSize, outputBuffering, determinerouteforebeappmiddleware, displayErrorDetails and so on, so that they are first loaded when the framework is loaded. You can use it directly,

The following is the loading mechanism:

<?phpnamespace Slim;use Interop\Container\ContainerInterface;use Interop\Container\Exception\ContainerException;use Pimple\Container as PimpleContainer;use Psr\Http\Message\ResponseInterface;use Psr\Http\Message\ServerRequestInterface;use Slim\Exception\ContainerValueNotFoundException;class Container extends PimpleContainer implements ContainerInterface{    /**     * Default settings     *     * @var array     */    private $defaultSettings = [        'httpVersion' => '1.1',        'responseChunkSize' => 4096,        'outputBuffering' => 'append',        'determineRouteBeforeAppMiddleware' => false,        'displayErrorDetails' => false,    ];    /**     * Create new container     *     * @param array $values The parameters or objects.     */    public function __construct(array $values = [])    {        //var_dump($values);          exit;        parent::__construct($values);        $userSettings = isset($values['settings']) ? $values['settings'] : [];        $this->registerDefaultServices($userSettings);    }    private function registerDefaultServices($userSettings)    {        $defaultSettings = $this->defaultSettings;        $this['settings'] = function () use ($userSettings, $defaultSettings) {            return new Collection(array_merge($defaultSettings, $userSettings));        };                $defaultProvider = new DefaultServicesProvider();        $defaultProvider->register($this);    }      . . .}

Here, defaultSettings is the default system configuration, and userSettings is the user configuration, such as logs and templates.

The following section uses offsetGet to judge whether the value has been set. If it has been set, it will be retrieved directly. If it is not set, it will be transferred to the set logic.

 1     public function offsetGet($id) 2     { 3         if (!isset($this->keys[$id])) { 4             throw new \InvalidArgumentException(sprintf('Identifier "%s" is not defined.', $id)); 5         } 6  7         if ( 8             isset($this->raw[$id]) 9             || !is_object($this->values[$id])10             || isset($this->protected[$this->values[$id]])11             || !method_exists($this->values[$id], '__invoke')12         ) {13             return $this->values[$id];14         }15 16         if (isset($this->factories[$this->values[$id]])) {17             return $this->values[$id]($this);18         }19 20         $raw = $this->values[$id];21         $val = $this->values[$id] = $raw($this);22         $this->raw[$id] = $raw;23 24         $this->frozen[$id] = true;25 26         return $val;27     }

Let's take a look at PimpleContainer, such:

We can see that SplObjectStorage is used to store a group of objects. When you need to uniquely identify objects. According to the official website, the PHP SplObjectStorage class implements the Countable, Iterator, Serializable, and ArrayAccess interfaces to implement functions such as statistics, iteration, serialization, and array access. Therefore, SplObjectStorage is a standard object container.

Speaking of this, you should have some knowledge about ArrayAccess. If you are not clear about it, you can take a look at the Slim source code. The above code is clear, and the source code is concise and worth learning.

The blog will be updated to my personal website at the same time. You are welcome to visit it!

Please indicate the source for reprinting, which will be updated continuously later. Thank you!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.