ZF2为整个应用程序设置全局功能

时间:2015-07-13 07:35:55

标签: php function zend-framework zend-framework2 global

对于我的应用程序,我编写了一个将字符串转换为SEO证明slug / url的函数。我在不同的模块中使用该函数,但是现在我在控制器或数据库模型中反复定义函数。

我想知道如何将此功能设置为一次并在整个应用程序中使用它(以正确的方式)。

谢谢! :)

4 个答案:

答案 0 :(得分:1)

创建服务,但不要使用闭包。闭包不会缓存。

<强> module.config.php

use Application\Service\SeoService;
use Application\Factory\Service\SeoService;

//...

    'service_manager' => [
        'factories' => [
            SeoService::class => SeoServiceFactory::class,
        ],
    ],

然后编写SeoService工厂和SeoService类:

<强>工厂

namespace Application\Factory\Service;

use Zend\ServiceManager\FactoryInterface;    
use Zend\ServiceManager\ServiceLocatorInterface;
use Application\Service\SeoService;

class SeoServiceFactory implements FactoryInterface {

    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $service = new SeoService( /* dependencies */ );
        return $service;           
    }
}

然后编写您的服务

<强>服务

namespace Application\Service\SeoService;

class SeoService
{

    public function __construct( /* dependencies */ ){

    }

    public function convertString( $url ){
        // do your thing here
    }
}

然后在您的控制器中,您将只是:

use Application\Service\SeoService;

$seo = $this->getServiceLocator()->get( SeoService::class );
$seo->convertString( ... );
祝你好运。

答案 1 :(得分:0)

Zend Plugins可以为您提供帮助。

有一些关于如何在那里创建自定义插件的好文章,here是开头的:)

基本上你需要采取以下3个步骤:

  1. 创建一个扩展Zend\Mvc\Controller\Plugin\AbstractPlugin
  2. 的插件类
  3. 将您的插件添加到&#39; invokables&#39;控制器的插件列表
  4. 在控制器中调用和使用您的插件,就像任何其他内置ZF2控制器一样

答案 2 :(得分:0)

没有正确的方法,因为你应该使用插件和DI系统中内置的ZF。

但是,您可以通过在index.php中添加此功能来实现您想要的效果。

警告,未经测试:

此外,您应该能够将其作为Factory添加到ServiceManager:

// in module.config.php
'service_manager' => array(
    'factories' => array(
        'somefunction' => function(){
            return function($param){
                return $param;
            };
        }
    )
)
// from service-manager
$fn = $sm->get('somefunction');
$fn('param');

答案 3 :(得分:0)

我看到很多有效的方法。

  1. 您可以定义类Tools之类的类,并在此类中将您的函数定义为静态方法。将来您可以在此类中定义更多类似的函数。并在任何地方拨打电话Tools::makeSlug();

  2. 另一种方法是使用此函数定义特征,并从此特征扩展您要使用函数的每个类,其中一个可能是您的makeSlug()函数。