PHP-DI is not working in integration with ZendFramework2 - php

Could you please give a hint why PHP-DI integration with Zend Framework 2 is not working for me (reproduced with Apache/2.4.9 (Win64) PHP/5.5.12 and Apache/2.2.22 (Win32) PHP/5.3.13).
composer.json:
{
"require": {
"php": ">=5.3.3",
"zendframework/zendframework": "2.3.5",
"mnapoli/php-di": "4.4.6",
"mnapoli/php-di-zf2": "0.3.0",
...
},
...
config\application.config.php:
<?php
return array(
'modules' => array(
'Morpho',
'DI\ZendFramework2',
),
'module_listener_options' => array(
'module_paths' => array(
'./module',
'./vendor',
),
),
);
?>
module/Morpho/config.module.config.php:
<?php
return array(
'service_manager' => array(
'factories' => array(
'DI\Container' => function() {
$builder = new DI\ContainerBuilder();
$builder->addDefinitionsFromFile("config/di.yml");
return $builder->build();
},
),
),
'router' => array(
...
),
'controllers' => array(
...
),
'view_manager' => array(
...
),
);
config/di.yml:
Morpho\Service\PartOfSpeechService:
class: Morpho\Service\PhpMorphyPartOfSpeechService
module/Morpho/src/Morpho/Controller/PartOfSpeechController:
class PartOfSpeechController extends AbstractRestfulController {
...
/**
* #Inject
* #var PartOfSpeechService
*/
public $partOfSpeechService;
public function processPostData(Request $request) {
$partsOfSpeech = $this->partOfSpeechService->getPartsOfSpeech("test", "en_EN");
return new JsonModel($partsOfSpeech);
}
}
When running this code under apache each time I get:
PHP Fatal error: Uncaught exception 'Zend\ModuleManager\Exception\RuntimeException'
with message 'Module (DI\ZendFramework2) could not be initialized.' in \vendor\zendframework\zendframework\library\Zend\ModuleManager\ModuleManager.php:195
Stack trace:
0 \vendor\zendframework\zendframework\library\Zend\ModuleManager\ModuleManager.php(169): Zend\ModuleManager\ModuleManager->loadModuleByName(Object(Zend\ModuleManager\ModuleEvent))
1 \vendor\zendframework\zendframework\library\Zend\ModuleManager\ModuleManager.php(96): Zend\ModuleManager\ModuleManager->loadModule('DI\ZendFramewor...')
2 [internal function]: Zend\ModuleManager\ModuleManager->onLoadModules(Object(Zend\ModuleManager\ModuleEvent))
3 \vendor\zendframework\zendframework\library\Zend\EventManager\EventManager.php(468):
call_user_func(Array, Object(Zend\ModuleManager\ModuleEvent))
4 \vendor\zendframework\zendframework\library\Zend\EventManager\EventManager.php(207): Zend\EventM in \vendor\zendframework\zendframework\library\Zend\ModuleManager\ModuleManager.php on line 195
Any your thoughts would be really appreciated.

It doesn't work because you are using the old YAML syntax, but since PHP-DI v4.0 the syntax is now PHP.
Head over to the documentation to learn about the syntax: http://php-di.org/doc/definition.html

For a service:
factory config:
'factories' => array(
'MyService' => 'Application\Factory\MyService',
),
Factory class:
class MyService implements FactoryInterface
{
public function createService(ServiceLocatorInterface $serviceManager)
{
$purifier = new MyService($serviceManager->get('MyAwesomeDependency'));
return $purifier;
}
}
For a controller:
ControllerFactory.php:
class PartOfSpeechControllerFactory
{
public function __invoke($serviceLocator)
{
// Service locator here is the ControllerManager so get ServiceManager
$serviceManager = $serviceLocator->getServiceLocator();
$controller = new PartOfSpeechController($serviceManager->get('PartOfSpeechService'));
return $controller;
}
}
class PartOfSpeechController.php
class PartOfSpeechController extends AbstractRestfulController {
protected $partOfSpeechService;
public function __construct(PartOfSpeechService $partOfSpeechService)
{
$this->partOfSpeechService = $partOfSpeechService;
}
public function processPostData(Request $request) {
$var = $this->partOfSpeechService->serviceMethod();
}
}
The config for controller:
'factories' => array(
'Application\Controller\PartOfSpeechController' => 'Application\Factory\PartOfSpeechControllerFactory'
),

I followed the suggestion given by Purple Hexagon and here is a working implementation using Service Manager:
module/Morpho/config:
...
'service_manager' => array(
'services' => array(
"PartOfSpeechService" => new Morpho\Service\PhpMorphyPartOfSpeechService(),
),
),
...
module/Morpho/src/Morpho/Controller/PartOfSpeechController.php:
class PartOfSpeechController extends AbstractRestfulController {
...
public function processPostData(Request $request) {
$serviceManager = $this->getServiceLocator();
$partsOfSpeech = $serviceManager->get("PartOfSpeechService")->getPartsOfSpeech($request->getPost("phrase"),
$request->getPost("language"));
return new JsonModel($partsOfSpeech);
}
}
Why I don't like this:
I have to use a "dummy" code to obtain serviceManager. That's "dummy" because that's not related to business logic of my application at all.
The Dependency Injection approach provided by ServiceManager makes my code dependent on the ServiceManager itself. Typically I should not care how a bean/object is injected and so shouldn't refer to any kind of container or ServiceManager in my code.
I think PHP-DI is much more closer to the bean injection model used by Java Spring (that I believe is good). Unfortunately it is still not working for me.
And finally, the approach of obtaining object from container was working in PHP-DI as well.

Related

Plugins not working in controller

I'm building my first Zend Framework 2 application with the skeleton tutorial. But whenever I try to call any plugin from any controller, I get the error message:
A plugin by the name "PLUGIN_NAME" was not found in the plugin manager
Zend\Mvc\Controller\PluginManager
Unfortunately I don't know which part of the code could help you to help me. I post some files which I think could be important.
config/modules.config
return [
'Zend\Router',
'Zend\Validator',
'Zend\Form',
'Album',
'Application',
'User',
];
module/User/src/Module.php
<?php
namespace User;
use User\Model\User;
use User\Model\UserTable;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
class Module
{
const VERSION = '1.0.0dev';
public function getAutoloaderConfig()
{
return array(
'Zend\Loader\ClassMapAutoloader' => array(
__DIR__ . '/autoload_classmap.php',
),
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
),
),
);
}
public function getConfig()
{
return include __DIR__ . '/../config/module.config.php';
}
public function getServiceConfig()
{
return array(
'factories' => array(
'User\Model\UserTable' => function($sm) {
$tableGateway = $sm->get('UserTableGateway');
$table = new UserTable($tableGateway);
return $table;
},
'UserTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new User());
return new TableGateway('user', $dbAdapter, null, $resultSetPrototype);
},
),
);
}
}
module/User/config/module.config.php
<?php
namespace User;
use Zend\ServiceManager\Factory\InvokableFactory;
use Zend\Router\Http\Segment;
return [
'controllers' => [
'factories' => [
Controller\UserController::class => InvokableFactory::class,
],
'invokables' => [
'User\Controller\User' => 'User\Controller\UserController',
],
],
'router' => [
'routes' => [
'user' => [
'type' => Segment::class,
'options' => [
'route' => '/user[/:action[/:id]]',
'constraints' => [
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[0-9]+',
],
'defaults' => [
'controller' => Controller\UserController::class,
'action' => 'index',
],
],
],
],
],
'view_manager' => [
'template_path_stack' => [
'user' => __DIR__ . '/../view',
],
],
];
I'm trying to call my plugins like this from a controller action:
$this->flashMessanger()->...
$this->identity();
$this->getServiceLocator();
Because I really needed the Service Locator, I found a workaround, which is not so nice I think, but works for me:
$sm = $this->getEvent()->getApplication()->getServiceManager();
But I guess something is wrong here.
Edit:
For a better reproduction of what I did (I installed Zend Framework again and it still gives me the same error):
Installed Zend Framework (2.4 I guess?) by this installation guide (https://framework.zend.com/manual/2.4/en/ref/installation.html). I installed it with the following command:
composer create-project -sdev --repository-url="https://packages.zendframework.com" zendframework/skeleton-application
On the installation, when I was asked if I want to install a minimum install, I chose "No". Every next question I answered with "Yes" (the installer asks to install a lot of modules, I installed them all).
The installer asked in which config I want to inject "ZendDeveloperTools". I answered 2 (config/development.config.php.dist). For all others I chose 1 (config/modules.config.php).
I tested the skeleton application by calling the url in my browser, it worked.
I downloaded the Album module from GitHub here (https://github.com/Hounddog/Album).
I copied the album module to my modules folder.
I added the entry 'Album' to my config/modules.config.php file
I browsed to the album page
I'm getting the error:
A plugin by the name "getServiceLocator" was not found in the plugin
manager Zend\Mvc\Controller\PluginManager
I assume the reason for this error is the getAlbumTable() method in the AlbumController
public function getAlbumTable()
{
if (!$this->albumTable) {
$sm = $this->getServiceLocator();
$this->albumTable = $sm->get('Album\Model\AlbumTable');
}
return $this->albumTable;
}
In the ZF2 docs for controller plugins you can read that your controller has to implement the following methods: setPluginManager, getPluginManager and plugin. You can also read:
For an extra layer of convenience, both AbstractActionController and AbstractActionController have __call() implementations that allow you to retrieve plugins via method calls:
$plugin = $this->url();
Does your controller extend AbstractActionController or AbstractActionController? If yes, it should work as mentioned in the docs (so those methods you mention in your question should work).
Since you didn't share any controller code it is hard to say whether this is the problem...
UPDATE
The error you get is not related to the configuration of your ControllerPluginManager, but you get this error because you are doing:
$sm = $this->getServiceLocator();
Since the method getServiceLocator doesn't exist the magic __call() method is executed and this leads to the error.
This is because in the latest versions of ZF2 the controller classes are no longer 'service locator aware' meaning you cannot retrieve the ServiceManager by calling $this->getServiceLocator().
Instead you will have to inject your Album\Model\AlbumTable service into the controller class inside a factory:
1) Add a constructor method to your controller class:
public function __construct(AlbumTable $albumTable){
$this->albumTable = $albumTable;
}
2) Create a factory for your controller:
<?php
namespace Album\Controller\Factory;
use Album\Controller\AlbumController;
class AlbumControllerFactory implements FactoryInterface
{
/**
* #param ServiceLocatorInterface $serviceLocator
* #return AlbumController
*/
public function createService(ServiceLocatorInterface $serviceLocator)
{
$controllerPluginManager = $serviceLocator;
$serviceManager = $controllerPluginManager->get('ServiceManager');
$albumTable = $serviceManager->get('Album\Model\AlbumTable');
return new AlbumController($albumTable);
}
}
3) Register your controller factory inside your module.config.php:
'factories' => [
`Album\Controller\AlbumController` => `Album\Controller\Factory\AlbumControllerFactory`,
],
The function getAlbumTable() was used in ZF2 tutorial but in ZF3 it was replaced by member table.
Change the deleteAction() function in AlbumController.php to read:
public function deleteAction()
{
$id = (int) $this->params()->fromRoute('id', 0);
if (!$id) {
return $this->redirect()->toRoute('album');
}
$request = $this->getRequest();
if ($request->isPost()) {
$del = $request->getPost('del', 'No');
if ($del == 'Yes') {
$id = (int) $request->getPost('id');
$this->table->deleteAlbum($id);
}
// Redirect to list of albums
return $this->redirect()->toRoute('album');
}
return array(
'id' => $id,
'album' => $this->table->getAlbum($id)
);
}
Note the two lines reading $this->table->... instead of $this->getAlbumTable()->...

Different uses of ServiceLocatorInterface in ZF2 Application

I have 2 factories.
The first is a Controller Factory:
<?php
namespace Blog\Factory;
use Blog\Controller\ListController;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class ListControllerFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $serviceLocator)
{
$realServiceLocator = $serviceLocator->getServiceLocator();
$postService = $realServiceLocator->get('Blog\Service\PostServiceInterface');
return new ListController($postService);
}
}
The second is a Post ServiceFactory:
<?php
namespace Blog\Factory;
use Blog\Service\PostService;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class PostServiceFactory implements FactoryInterface
{
/**
* Create service
*
* #param ServiceLocatorInterface $serviceLocator
* #return mixed
*/
public function createService(ServiceLocatorInterface $serviceLocator)
{
return new PostService(
$serviceLocator->get('Blog\Mapper\PostMapperInterface')
);
}
}
Here is my module config:
<?php
return array(
'service_manager' => array(
'factories' => array(
'Blog\Service\PostServiceInterface' => 'Blog\Factory\PostServiceFactory'
)
),
'controllers' => array(
'factories' => array(
'Blog\Controller\List' => 'Blog\Factory\ListControllerFactory'
)
),
'router' => array(
// Open configuration for all possible routes
'routes' => array(
// Define a new route called "post"
'post' => array(
// Define the routes type to be "Zend\Mvc\Router\Http\Literal", which is basically just a string
'type' => 'literal',
// Configure the route itself
'options' => array(
// Listen to "/blog" as uri
'route' => '/blog',
// Define default controller and action to be called when this route is matched
'defaults' => array(
'controller' => 'Blog\Controller\List',
'action' => 'index',
)
)
)
)
),
'view_manager' => array(
'template_path_stack' => array(
__DIR__ . '/../view',
),
)
);
In the controller factory, I have to call getServiceLocator against the ServiceLocatorInterface, followed by the get call. however in the post service factory i just call get. I did a dump and it looks like both are the Zend\ServiceManager\ServiceManager classes. When I tried performing the getServiceLocator call against the post service factory service locator it errored no method found.
Im not quite understanding whats going on?
Controller factories are called in a different way than casual service factories. The ServiceLocator passed to createService is actually not the ServiceManager you are looking for but an instance of ControllerManager.
If you try this:
public function createService(ServiceLocatorInterface $serviceLocator)
{
$realServiceLocator = $serviceLocator->getServiceLocator();
$postService = $realServiceLocator->get('Blog\Service\PostServiceInterface');
var_dump(get_class($serviceLocator));
return new ListController(postService );
}
you'll get the output:
string(37) "Zend\Mvc\Controller\ControllerManager"
while the same dump in your PostServiceFactory will give you:
string(34) "Zend\ServiceManager\ServiceManager"
From the Zend 2 documentation:
http://framework.zend.com/manual/current/en/in-depth-guide/services-and-servicemanager.html#writing-a-factory-class
When using a Factory-Class that will be called from the ControllerManager it will actually inject itself as the $serviceLocator. However, we need the real ServiceManager to get to our Service-Classes. This is why we call the function getServiceLocator() who will give us the real ServiceManager.

Zend 2 Dynamic Content in Layout with View Helpers

I'm new in Zend FW 2 and I try to showing data from database in layout but I receive error:
Catchable fatal error: Argument 1 passed to Application\View\Helper\HotNews::__construct() must be an instance of Zend\Db\Adapter\Adapter, none given, called in C:\xampp\htdocs\webtruonghoc\vendor\ZF2\library\Zend\ServiceManager\AbstractPluginManager.php on line 207 and defined in C:\xampp\htdocs\webtruonghoc\module\Application\src\Application\View\Helper\HotNews.php on li
Function getViewHelperConfig in Module.php:
public function getViewHelperConfig()
{
return array(
'factories' => array(
'hotNews' => function($sm) {
$adapter = $sm->getServiceLocator()->get('Application\Model\NewsTable');
return new HotNews($adapter);
},
),
);
}
Add code in module.config.php:
'view_helpers' => array(
'invokables' => array(
'hotnews' => 'Application\View\Helper\HotNews',
),
File HotNews.php:
<?php
namespace Application\View\Helper;
use Zend\Authentication\AuthenticationService;
use Zend\View\Helper\AbstractHelper;
use Zend\Db\Adapter\Adapter;
class HotNews extends AbstractHelper
{
protected $adapter;
public function __construct(Adapter $adapter)
{
$this->adapter = $adapter;
}
public function __invoke()
{
$sql="SELECT * FROM news order by date DESC limit 0,4";
return $resultSet = $this->adapter->query($sql, \Zend\Db\Adapter\Adapter::QUERY_MODE_EXECUTE);
}
}
and final I showing data in layout:
<?php $hotnews = $this->hotNews();
var_dump($hotnews);
?>
Do I miss something?
It looks like you are expecting your model to be set up as a service. but may not have set up the service correctly. In your module.config.php file, there should be an entry under 'service_manager' => 'factories' :
return array(
'service_manager' => array(
'factories' => array(
'Application\Model\NewsTable' => function (ServiceLocatorInterface $serviceLocator) {
//... returns an instance of Application\Model\NewsTable
}
)
)
);
Your SQL has an error in it. Also, you should not be executing SQL statements inside a view helper, and passing the entire result set of a select * to the view is bad JuJu as well. I would place the SQL inside a Repository class which returns DTO objects representing your data model. You could then inject the repository into your ViewHelper and and use those DTOs in your view.

ZF 2 - Fatal Error: Call to a member function getPosts() on null

I am creating a website using Zend Framework 2, and I'm using as an example the exercise from the official course of Zend Technology, Zend Framework 2: Fundamentals.
I have a table called posts and I want to show the table content in my home page, ordered by id. These are the codes I have written:
Controller/PostsTableTrait.php
trait PostsTableTrait
{
private $postsTable;
public function setPostsTable($postsTable)
{
$this->postsTable = $postsTable;
}
}
Controller/IndexController.php
class IndexController extends AbstractActionController
{
use PostsTableTrait;
public function indexAction()
{
return new ViewModel(array(
'post' => $this->postsTable->getPosts()
));
}
}
Factory/IndexControllerFactory.php
class IndexControllerFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $serviceLocator)
{
$serviceManager = $serviceLocator->getServiceLocator()->get('ServiceManager');
$indexController = new IndexController();
$indexController->setPostsTable($serviceManager->get('Rxe\Factory\PostsTable'));
return $indexController;
}
}
Factory/PostsTableFactory.php
class PostsTableFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $serviceLocator)
{
return new PostsTable(PostsTable::$tableName, $serviceLocator->get('Zend\Db\Adapter\AdapterService'));
}
}
Model/PostsTable.php
class PostsTable extends TableGateway
{
public static $tableName = "posts";
public function getPosts()
{
$select = new Select(self::$tableName);
$select->columns(array(
'date',
'title',
'text',
'category'
));
$select->order('id DESC');
return $select;
}
}
config/module.config.php
'controllers' => array(
'invokables' => array(
'Rxe\Controller\Index' => 'Rxe\Controller\IndexController',
'Rxe\Controller\Panel' => 'Rxe\Controller\PanelController'
),
'factories' => array(
'Rxe\Factory\PanelController' => 'Rxe\Factory\PanelControllerFactory'
)
),
'service_manager' => array(
'factories' => array(
'Rxe\Factory\PanelForm' => 'Rxe\Factory\PanelFormFactory',
'Rxe\Factory\PanelFilter' => 'Rxe\Factory\PanelFilterFactory',
'Rxe\Factory\PostsTable' => 'Rxe\Factory\PostsTableFactory',
'Zend\Db\Adapter\AdapterService' => 'Zend\Db\Adapter\AdapterServiceFactory'
)
),
I don't know if the error could be in the getPosts() method. I have tried many different ways to return the query but none of them made any difference, not even showed another error.
You have registered the controller as an 'invokable'. When the the controller manager creates IndexController it will do so without using the IndexControllerFactory; therefore the Rxe\Factory\PostsTable dependency is never set.
To fix this, update module.config.php and register the index controller with your factory class.
'controllers' => [
'factories' => [
'Rxe\Controller\Index' => 'Rxe\Factory\IndexControllerFactory',
],
],
Also (not an error as such) but the IndexControllerFactory calls ->get('ServiceManager') using the service manager.
You could update it to be like this.
class IndexControllerFactory implements FactoryInterface
{
public function createService(ServiceLocatorInterface $controllerManager)
{
// #var \Zend\ServiceManager\ServiceManager
$serviceManager = $controllerManager->getServiceLocator();
$indexController = new IndexController();
$indexController->setPostsTable($serviceManager->get('Rxe\Factory\PostsTable'));
return $indexController;
}
}

how to create a factory in zend framework 2?

in my Module.php i have the fallowing methods that i would like to move them in a factory class so that i wont clutter the Module class:
public function getControllerConfig()
{
return array(
'factories' => array(
'account-index' => function ($controllerManager) {
$serviceManager = $controllerManager->getServiceLocator();
$accountService = $serviceManager->get('account-service');
return new Controller\IndexController($accountService);
}
)
);
}
public function getServiceConfig()
{
return array(
'factories' => array(
'account-service' => function ($serviceManages) {
return new Service\Account;
}
)
);
}
right now i have:
and where shall i put this factory class, maybe in a Factory folder?
any ideas?
I usually put my factories into ../module/yourmodule/src/yourmodule/Factory.
in your ../module/yourmodule/config/module.config.php you then have to configure your service_manager like so:
'service_manager' => array(
'factories' => array(
'yourfactory' => 'yourmodule\Factory\yourfactory',
),
),
in yourfactory.php You then have to implent the FactoryInterface and set the service locator. Once you done this you should be able to call the service the usual way for controllers, forms etc.
namespace Application\Factory;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class yourfactory implements FactoryInterface
{
private $config;
private $serviceLocator;
public function createService(ServiceLocatorInterface $serviceLocator)
{
return $servicelocator->get('Your\Service');
}
After that you can just define functions in your yourfactory.php. In your Controller you call functions like so $serviceManager->get('yourfactory')->yourfunction(yourarguments);

Categories