For my application I have written a function which convert strings into SEO proof slug's/urls. I am using the function in different modules but for now I define the function over and over again in the controller or in a database model.
I am wondering how it is possible to set this function just once and use it in the whole application (in the right way).
Thanks you! :)
Create a service, but don't use a closure. Closures don't cache.
module.config.php
use Application\Service\SeoService;
use Application\Factory\Service\SeoService;
//...
'service_manager' => [
'factories' => [
SeoService::class => SeoServiceFactory::class,
],
],
Then write your SeoService factory and your SeoService class:
Factory
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;
}
}
Then write your service
Service
namespace Application\Service\SeoService;
class SeoService
{
public function __construct( /* dependencies */ ){
}
public function convertString( $url ){
// do your thing here
}
}
So then in your controllers, you will just:
use Application\Service\SeoService;
$seo = $this->getServiceLocator()->get( SeoService::class );
$seo->convertString( ... );
Good luck.
Zend Plugins can assist you with this.
There are some good articles on how to create a custom plugin out there, here is one to begin with :)
Basically you need take the following 3 steps:
Zend\\Mvc\\Controller\\Plugin\\AbstractPlugin
There is no right way to do this, because you should use ZFs built in Plugin and DI System.
But you could achieve what you want by adding this function in your index.php
.
Warning, not tested:
Also you should be able to add this as Factory to 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');
I see many valid approaches for this.
You could define class something like Tools
and in this class define your function as static method. In future you can define more similar functions in this class. And call wherever you want Tools::makeSlug();
Another approach is to define trait with this function and extends every class where you want to use function from this trait, one of them could be your makeSlug()
function.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.