我在Zend Framework 2中使用MVC架构开发了一个应用程序。
我有一个电子邮件,这是发送给管理员,现在需要附加一个超链接,将有基本路径包含在其中。
我所有的业务逻辑都是在服务层处理的,它不使用查看器。
有什么建议的解决方案吗?
听起来你应该从控制器中注入一个依赖项到你的服务对象中。像那样向后工作不是一个好的练习。既然你提到你正在利用MVC,我想这是一个控制器动作,而不是CLI命令?所以这样做:
控制器use 'Application'Service'Bar;
public function fooAction(){
$bar_with_basepath = $this->getServiceLocator()->get( Bar::class, ['basepath' => $this->basePath() ] );
$bar_with_basepath->execute();
}
下一步,将你的服务链接到一个工厂
配置
use 'Application'Service'Bar;
use 'Application'Factory'Service'BarFactory;
...
'service_manager' => [
'factories' => [
Bar::class => BarFactory::class,
],
],
然后,定义你的工厂代码,包括MutableCreationOptions
use Zend'ServiceManager'FactoryInterface;
use Zend'ServiceManager'MutableCreationOptionsInterface;
class BarFactory implements FactoryInterface, MutableCreationOptionsInterface{
protected $options;
public function setCreationOptions( array $options )
{
$this->options = $options;
}
/**
* {@inheritdoc}
*/
public function createService(ServiceLocatorInterface $serviceLocator)
{
$serviceManager = $serviceLocator->getServiceLocator();
$bar = new Bar( $this->options['basepath'] );
return $bar;
}
}
现在,你可以保证基路径将被传递给Bar服务的构造函数。
class Bar {
public $basepath;
public function __construct( $basepath ){
$this->basepath = $basepath;
}
public function execute(){
// do something with the basepath
}
}
你需要处理从你的工厂获取任何其他依赖到你的服务(上面的栏)。例如,设置服务定位器等(现在使用ServiceLocatorAwareTrait非常容易)。
总是注入你的依赖项,不要试图反向工程它们:)