GetServiceLocator in Zend Framework 3

前端 未结 1 700
情话喂你
情话喂你 2021-01-28 02:15

Good morning, i have been learning to program using a framework (Zend Framework). In my past experiences i was using a skeleton application v.2.5. That been said, all my past de

1条回答
  •  醉梦人生
    2021-01-28 02:47

    There is no more service locator in ZF3 as it is considered as an antipattern.

    The proper way to proceed is to use factories in the service manager, and pass specific dependencies into your class.

    If you have any code you can show, I'll be happy to help you further.


    Edit according to the example provided.

    First thing first, use composer for autoloading rather than the old Zend stuff. In Module.php, remove the autoloading. Removing the autoload_classmap file is also required.

    Add a composer.json file and set your PSR-0 or PSR-4 autoloading (ask if you don't know how).

    Back on the Module class, you also need to change the service manager configuration. I'm keeping your anonymous functions here but you should use proper classes.

     [
                    \SanAuth\Model\MyAuthStorage::class => function($container){
                        return new \SanAuth\Model\MyAuthStorage('zf_tutorial');
                    },
                    'AuthService' => function($container) {
                        $dbAdapter = $sm->get(\Zend\Db\Adapter\Adapter::class);
                        $dbTableAuthAdapter = new DbTableAuthAdapter($dbAdapter, 'users','user_name','pass_word', 'MD5(?)');
                        $authService = new AuthenticationService();
                        $authService->setAdapter($dbTableAuthAdapter);
                        $authService->setStorage($container->get(SanAuth\Model\MyAuthStorage::class));
    
                        return $authService;
                    },
                ),
            );
        }
    }
    

    Also, please consider using password_* functions rather than MD5 (or whatever, but not md5 anyways).

    Let's focus on just one simple controller. Same things needs to be repeated for the others.

    authenticationService = $authenticationService;
        }
    
        public function indexAction()
        {
            if (! $this->authenticationService->hasIdentity()){
                return $this->redirect()->toRoute('login');
            }
    
            return new ViewModel();
        }
    }
    

    Obviously you need to update the factory: https://github.com/samsonasik/SanAuth/blob/master/config/module.config.php#L10 (inject the service as parameter).

    Looking at the code on github, the master branch introduces ZF3 compatibility from what I can see, so have a look there!

    0 讨论(0)
提交回复
热议问题