The dependency injection in Slim was based on pimple, so he went on to learn about pimple. Compared to the dependency injection class that I wrote before, Pimple has a very fresh usage, not using
$container->session_storage = function ($c) { return new $c [' Session_storage_class '] ($c [' cookie_name ']);};
Instead, it is injected in an array way:
$container [' session_storage '] = function ($c) { return new $c [' Session_storage_class '] ($c [' cookie_name ']);};
Look at the source of the original trick is found in the PHP5 provided by the Arrayaccess interface.
Official definition: An interface that provides the ability to access objects like an array.
The interface mainly defines four abstract methods:
The abstract public boolean offsetexists (mixed $offset) #检查数据是否存在abstract the public mixed offsetget (mixed $offset) #获取数 According to the abstract public void Offsetset (mixed $offset, mixed $value) #设置数据 the abstract public void Offsetunset (mixed $o Ffset) #删除数据
If you want the object to be used like a PHP array, then we need to implement the Arrayaccess interface.
The code is as follows:
Interface Arrayaccess Boolean offsetexists ($index) mixed offsetget ($index) void Offsetset ($index, $newvalue) void Offsetunset ($index)
The following example shows how to use this interface, but the example is not complete, but it is enough to read,:->
The code is as follows:
<?php class Usertosocialsecurity implements arrayaccess {private $db;//An object that contains the method of accessing the database function offsetexists ($name) {return $this->db->userexists ($name);} function Offsetget ($name) {return $this->db->getuserid ($name),} function Offsetset ($name, $id) {$this->db-& Gt;setuserid ($name, $id); } function Offsetunset ($name) {$this->db->removeuser ($name);}} $userMap = new Usertosocialsecurity (); Print "John ' s ID number is". $userMap [' John '];?>
In fact, when the $userMap [' John '] lookup is executed, PHP calls the Offsetget () method, which again calls the database-related getUserId () method.