如何让serviceManager处理类zf2

时间:2015-02-21 22:16:19

标签: php zend-framework2 apigility

我在module.php上定义了一些服务,按预期工作:

public function getServiceConfig()
{
    return array(
        'factories' => array(
            'Marketplace\V1\Rest\Service\ServiceCollection' =>  function($sm) {
                    $tableGateway = $sm->get('ServiceCollectionGateway');
                    $table = new ServiceCollection($tableGateway);
                    return $table;
                },
            'ServiceCollectionGateway' => function ($sm) {
                    $dbAdapter = $sm->get('PdoAdapter');
                    $resultSetPrototype = new ResultSet();
                    $resultSetPrototype->setArrayObjectPrototype(new ServiceEntity());
                    return new TableGateway('service', $dbAdapter, null, $resultSetPrototype);
                },
            'Marketplace\V1\Rest\User\UserCollection' =>  function($sm) {
                    $tableGateway = $sm->get('UserCollectionGateway');
                    $table = new UserCollection($tableGateway);
                    return $table;
                },
            'UserCollectionGateway' => function ($sm) {
                    $dbAdapter = $sm->get('PdoAdapter');
                    $resultSetPrototype = new ResultSet();
                    $resultSetPrototype->setArrayObjectPrototype(new UserEntity());
                    return new TableGateway('user', $dbAdapter, null, $resultSetPrototype);
                },
        ),
    );
}

我使用它们将我的数据库表映射到一个对象。从我项目的主要课程中,我可以毫无问题地访问它们。看一下我的项目文件树:

enter image description here

例如,userResource.php扩展了abstractResource,这个函数有效:

public function fetch($id)
{
    $result = $this->getUserCollection()->findOne(['id'=>$id]);
    return $result;
}

在ResourceAbstract内部,我有:

<?php

namespace Marketplace\V1\Abstracts;

use ZF\Rest\AbstractResourceListener;
use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class ResourceAbstract extends AbstractResourceListener implements ServiceLocatorAwareInterface {

    protected $serviceLocator;


    public function getServiceCollection() {
        $sm = $this->getServiceLocator();
        return $sm->get('Marketplace\V1\Rest\Service\ServiceCollection');
    }

    public function getUserCollection() {
        $sm = $this->getServiceLocator();
        return $sm->get('Marketplace\V1\Rest\User\UserCollection');
    }

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

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

} 

根据Zf2文档的建议,我需要实现ServiceLocatorAwareInterface才能使用serviceManager。到现在为止还挺好。然后我决定添加一个新类,调用Auth。

这个类与abstractResource没什么不同,它在loginController中调用如下:

<?php
namespace Marketplace\V1\Rpc\Login;

use Zend\Mvc\Controller\AbstractActionController;
use Marketplace\V1\Functions\Auth;

class LoginController extends AbstractActionController
{
    public function loginAction()
    {
        $auth = new Auth();
        $data = $this->params()->fromPost();
        var_dump($auth->checkPassword($data['email'], $data['password']));

        die;
    }


}

这是Auth:

<?php

namespace Marketplace\V1\Functions;


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

class Auth implements ServiceLocatorAwareInterface {

    protected $serviceLocator;

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

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

    public function checkPassword($email, $rawPassword) {

        $user = $this->getServiceLocator()->get('Marketplace\V1\Rest\User\UserCollection')->findByEmail($email);
        if($user)
            return false;

        $result = $this->genPassword($rawPassword, $user->salt);

        if($result['password'] === $user->password)
            return true;
        else
            return false;

    }

    public function genPassword($rawPassword, $salt = null) {
        if(!$salt)
            $salt = mcrypt_create_iv(22, MCRYPT_DEV_URANDOM);
        $options = [
            'cost' => 11,
            'salt' => $salt,
        ];
        return ['password' => password_hash($rawPassword, PASSWORD_BCRYPT, $options), 'salt' => bin2hex($salt)];
    }

}

正如你所看到的,它遵循abtractResource所做的相同路径,但是,在这种情况下,当我执行loginController时,我收到一个错误:

Fatal error</b>:  Call to a member function get() on null in C:\WT-NMP\WWW\MarketPlaceApi\module\Marketplace\src\Marketplace\V1\Functions\Auth.php on line 25

这就是指这一行:$user = $this->getServiceLocator()->get('Marketplace\V1\Rest\User\UserCollection')->findByEmail($email);

表示getServiceLocator为空。为什么我不能让serviceLocator在Auth类上工作,但我可以在abstractResource中工作?

1 个答案:

答案 0 :(得分:2)

那是因为ServiceLocator是通过一种名为“setter injection&#39;”的机制注入的。要实现这一点,某些事情(例如,ServiceManager)需要为类调用setter,在本例中为setServiceLocator。当您直接实例化Auth时,并非如此。您需要将您的类添加到服务定位器,例如作为可调用的服务。

E.g:

public function getServiceConfig()
{
    return array(
        'invokables' => array(
            'Auth' => '\Marketplace\V1\Functions\Auth',
        ),
    );
}

或者,因为它没有为工厂使用匿名函数,所以将它放在你的模块配置文件`modules / Marketplace / config / module.config.php&#39;:

中。
// ... 
'service_manager' => array(
    'invokables' => array(
        'Auth' => '\Marketplace\V1\Functions\Auth',
    ),
),

您可以从控制器中的服务定位器获取Auth

$auth = $this->getServiceLocator()->get('Auth');

而不是:

$auth = new Auth;

这样服务定位器将为您构造Auth,检查它实现的接口以及何时发现它实现了ServiceLocatorAwareInterface然后它运行setter传递一个实例本身就是它。有趣的事实:控制器本身以相同的方式注入服务定位器的实例(它是实现完全相同接口的this class的祖先)。另一个有趣的事实:这种行为将来可能会改变为discussed here