slim中的依賴注入基於pimple,於是又去學習了一下pimple。 對比之前自己寫的依賴注入類,pimple有一個很新鮮的用法,不是採用
$container->session_storage = function ($c) { return new $c['session_storage_class']($c['cookie_name']);};
而是以數組方式進行注入:
$container['session_storage'] = function ($c) { return new $c['session_storage_class']($c['cookie_name']);};
看源碼時才發現原來訣竅就在php5提供的ArrayAccess介面上。
官方定義:提供像訪問數組一樣訪問對象的能力的介面。
該介面主要定義了四個抽象方法:
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 ) #刪除資料
如果想讓對象使用起來像一個 PHP 數組,那麼我們需要實現 ArrayAccess 介面
代碼如下:
interface ArrayAccess boolean offsetExists($index) mixed offsetGet($index) void offsetSet($index, $newvalue) void offsetUnset($index)
下面的例子展示了如何使用這個介面,例子並不是完整的,但是足夠看懂,:->
代碼如下:
<?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']; ?>
實際上,當 $userMap['John'] 尋找被執行時,PHP 調用了 offsetGet() 方法,由這個方法再來調用資料庫相關的 getUserId() 方法。