2015-01-06 44 views
1

在兩天中的較好時間裏,我一直在絞盡腦汁。我正在使用Zend Apigility創建一個RESTful Web API應用程序。 Apigility使用ZF2構建應用程序。ZF2在自定義類中獲取自動加載的配置信息

我創建了一個我在我的API中使用的自定義類。

我想讀取一些自動加載的配置信息來建立到memcache服務器的連接。正被自動加載到服務管理的文件是:

memcache.config.local.php:我的REST服務都呼籲被稱爲checkAuth

return array(
    'memcache' => array(
     'server' => '10.70.2.86', 
     'port' => '11211', 
), 
); 

我的自定義類:

checkAuth.php:

namespace equiAuth\V1\Rest\AuthTools; 

use Zend\ServiceManager\ServiceLocatorAwareInterface; 
use Zend\ServiceManager\ServiceLocatorInterface; 

class checkAuth implements ServiceLocatorAwareInterface{ 

    protected $services; 

    public function setServiceLocator(ServiceLocatorInterface $serviceLocator) 
    { 
     $this->services = $serviceLocator; 
    } 

    public function getServiceLocator() 
    { 
     return $this->services; 
    } 

    public function userAuths() { 
     //** Some Code 

     $config = $this->getServiceLocator()->get('config'); 

     // ** 
    } 
} 

我相信我注入服務經理成從我module.config.php類用下面的代碼:

'service_manager' => array(
    'invokables' => array(
     'checkAuth' => 'equiAuth\V1\Rest\AuthTools\checkAuth', 
    ), 
), 

當我打的時候,我試圖讀取從服務定位器我得到的get方法的「配置」的代碼以下錯誤:

Fatal error: Call to a member function get() on a non-object

我知道我錯過了一些東西,但我不能爲我的生活找出什麼。

回答

0

給你的班級一個API,允許你從客戶端代碼'設置'配置。這可以通過建設者或公共設置者。

namespace equiAuth\V1\Rest\AuthTools; 

class CheckAuth 
{ 
    protected $config; 

    public function __construct(array $config = array()) 
    { 
     $this->setConfig($config); 
    } 

    public function setConfig(array $config) 
    { 
     $this->config = $config; 
    } 

    public function doStuff() 
    { 
     $server = $this->config['server']; 
    } 

} 

爲了'設置'配置,你還需要創建一個服務工廠類。工廠的想法是爲您提供一個區域來將配置注入到服務中;與上面的更新CheckAuth我們現在可以很容易地做到這一點。

namespace equiAuth\V1\Rest\AuthTools; 

use equiAuth\V1\Rest\AuthTools\CheckAuth; 
use Zend\ServiceManager\ServiceLocatorInterface; 
use Zend\ServiceManager\FactoryInterface; 

class CheckAuthFactory implements FactoryInterface 
{ 
    public function createService(ServiceLocatorInterface $serviceLocator) 
    { 
     $config = $serviceLocator->get('config'); 

     return new CheckAuth($config['memcache']); 
    } 
} 

最後,用服務管理器更改註冊的服務;這裏的變化是服務密鑰表格invokablesfactories,因爲我們需要在工廠上面註冊 來創建它。

// module.config.php 
'service_manager' => array(
    'factories' => array(
     'checkAuth' => 'equiAuth\V1\Rest\AuthTools\CheckAuthFactory', 
    ), 
), 
0

ZF2也使用ServiceManager容器。

你的代碼是正確的,而是 要自動注入服務定位上的類,你只需要使用

$checkAuth = $this->getServiceLocator()->get('checkAuth'); 

,那麼你可以調用

$checkAuth->userAuths(); 

,並應工作。

如果您嘗試使用:

$checkAuth = new \equiAuth\V1\Rest\AuthTools\checkAuth(); 
$checkAuth->userAuths(); //error 

不會起作用,因爲什麼注射服務定位到你的類只是 的ServiceManager,一旦你使用的ServiceManager你需要傳道他們。

但是,如果你嘗試:

$checkAuth = new \equiAuth\V1\Rest\AuthTools\checkAuth(); 
$checkAuth->setServiceLocator($serviceLocator) 
//get $serviceLocator from ServiceManager Container 
$checkAuth->userAuths(); 

也能工作。

幹得好!

相關問題