The dependency injection in slim is based on pimple, so I went to learn pimple again. Compared with the dependency injection class I wrote before, pimple has a very new usage. Instead of using
$container->session_storage = function ($c) { return new $c['session_storage_class']($c['cookie_name']); };
, it is injected in an array:
$container['session_storage'] = function ($c) { return new $c['session_storage_class']($c['cookie_name']); };
When I looked at the source code, I realized that the trick is On the ArrayAccess interface provided by php5.
Official definition: An interface that provides the ability to access objects like accessing arrays.
This interface mainly defines four abstract methods:
abstract public boolean offsetExists ( mixed $offset ) #检查数据是否存在 abstract public mixed offsetGet ( mixed $offset ) #获取数据 abstract public void offsetSet ( mixed $offset , mixed $value ) #设置数据 abstract public void offsetUnset ( mixed $offset ) #删除数据
If you want the object to be used like a PHP array, then we need to implement 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. The example is not complete, but it is enough to understand, :->
The code is as follows:
<?php class UserToSocialSecurity implements ArrayAccess { private $db;//一个包含着数据库访问方法的对象 function offsetExists($name) { return $this->db->userExists($name); } function offsetGet($name) { return $this->db->getUserId($name); } function offsetSet($name, $id) { $this->db->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'] search is executed, PHP calls the offsetGet() method, which is then called Database-related getUserId() method.
The above is the detailed content of Detailed code explanation of the ArrayAccess interface in php. For more information, please follow other related articles on the PHP Chinese website!