The valid pattern for ZF3 service DI for interconnected services - php

As far as I understand the valid pattern is:
a FooControllerFactory that instantiates the needed service(s) (FooService)
a FooController with constructor __construct(FooService $fooService)
the Controller acquires some basic data and gets a result from the service
the Service contains all the required business logic
This is a base service. Eventualy this service will need other services for various activities.
For example CacheService, SomeOtherDataService.
The question is, what is a valid/appropriate pattern for
including/injecting those other interconnected services?
A reallife example of that we have currently, extremely simplified:
AuctionController
/**
* get vehicles for specific auction
*/
public function getVehiclesAction ()
{
$auctionService = $this->getAuctionService(); // via service locator
$auctionID = (int) $this->params('auction-id');
$auction = $auctionService->getAuctionVehicle($auctionID);
return $auction->getVehicles();
}
AuctionService
public function getAuctionVehicles($auctionID) {
$auction = $this->getAuction($auctionID);
// verify auction (active, permissions, ...)
if ($auction) {
$vehicleService = $this->getVehicleService(); // via service locator
$vehicleService->getVehicles($params); // $params = some various conditions or array of IDs
}
return false;
}
VehicleService
public function getVehicles($params) {
$cache = $this->getCache(); // via service locator
$vehicles = $cache->getItem($params);
if (!$vehicles) {
$vehicleDB = $this->getVehicleDB(); // via service locator
$vehicles = $vehicleDB->getVehicles($params);
}
return $vehicles;
}
Example of a suggested valid pattern
AuctionController
public function __construct(AuctionService $auctionService) {
$this->auctionService = $auctionService;
}
/**
* get vehicles for specific auction
*/
public function getVehiclesAction ()
{
$auctionID = (int) $this->params('auction-id');
$auction = $this->auctionService->getAuctionVehicle($auctionID);
return $auction->getVehicles();
}
**AuctionService**
public function getAuctionVehicles($auctionID) {
$auction = $this->getAuction($auctionID); // no problem, local function
// verify auction (active, permissions, ...)
if ($auction) {
$vehicleService = $this->getVehicleService(); // we don't have service locator
$vehicleService->getVehicles($params); // $params = some various conditions or array of IDs
}
return false;
}
VehicleService
public function getVehicles($params) {
$cache = $this->getCache(); // we don't have service locator, but cache is probably static?
$vehicles = $cache->getItem($params);
if (!$vehicles) {
$vehicleDB = $this->getVehicleDB(); // where and how do we get this service
$vehicles = $vehicleDB->getVehicles($params);
}
return $vehicles;
}
Some notes:
Services are interconnected only in some cases, in 95% they are standalone
Auction has a lot funcionality that does not need Vehicle
Vehicle has VehicleController and VehicleService that does only in some cases relate do Auction, it's a standalone module that has other functionalities
The Injection of every needed service in a controller would be a waste of resources, because they are not needed in every action (in the real-life application we have many more interconnected services, not just two)
Programming the same business logic in multiple services just to avoid the service locator is obviously an invalid pattern and not acceptable.

If a controller requires too many different services, it usually is an indicator that the controller has too many responsibilities.
Following up on #AlexP's answer, this service then would be injected in your controller. Depending on your setup, this sure can result in dependecy injection cascades when a controller is created. This at least will limit the created services to those that are actually required by the controller (and those related transitively).
If some of these services are only required rarely and you are worried about creating them all on each request, the new Service Manager now supports lazy services too. Those still can be injected into a service / controller as a regular dependency (as above), but are only created when called for the first time.
Copying this from the documentation's example:
$serviceManager = new \Zend\ServiceManager\ServiceManager([
'factories' => [
Buzzer::class => InvokableFactory::class,
],
'lazy_services' => [
// Mapping services to their class names is required
// since the ServiceManager is not a declarative DIC.
'class_map' => [
Buzzer::class => Buzzer::class,
],
],
'delegators' => [
Buzzer::class => [
LazyServiceFactory::class,
],
],
]);
When requesting the service, it does not get created right away:
$buzzer = $serviceManager->get(Buzzer::class);
But only when it is first used:
$buzzer->buz();
This way you can inject multiple dependencies into your controller and only the services actually required will be created. Of course this is true for any dependency, like Services required by other services and so on.

You could compose a new service, say VehicleAuctionService and have both the AuctionService and VehicleService injected as dependancies using a factory.
This is object composition.
class VehicleAuctionService
{
private $auctionService;
private $vehicleService;
public function __construct(
AuctionService $auctionService,
VehicleService $vehicleService
){
$this->auctionService = $auctionService;
$this->vehicleService = $vehicleService;
}
public function getAuctionVehicles($auctionID)
{
$auction = $this->auctionService->getAuction($auctionID);
if ($auction) {
$params = [
'foo' => 'bar',
];
$this->vehicleService->getVehicles($params);
}
return false;
}
}

Related

Laravel - Sending customized Bugsnag error reports based on exception type?

I have a Laravel 7 app that uses a 3rd party PHP package to integrate with a service (Convirza). I bootstrapped and bound the service into the container via my own service provider App\Providers\ConvirzaServiceProvider. My problem is that I need to send error logs from the service to Bugsnag (error reporting service)... and depending on the Exception thrown from the service, I need to add metadata to the report. I do NOT want to filter exceptions from the base App\Exceptions\Handler class because I want everything to be wrapped into the Service Provider.
For example, when the Skidaatl\Convirza\Exceptions\BadRequestException gets thrown, I want to add the request parameters as metadata to the report. Another example would be if the Skidaatl\Convirza\Exceptions\InvalidTokenException gets thrown, I want to add the token as metadata to my report.
I would rather not add a try/catch block every time I call the service. How would I go about this?
Here is my Service Provider:
class ConvirzaServiceProvider extends ServiceProvider
{
/**
* Bootstrap services.
*
* #return void
*/
public function boot()
{
if ($this->app->runningInConsole()) {
$this->commands([
Commands\UpdateCampaignsCommand::class,
Commands\UpdateGroupsCommand::class,
Commands\GenerateReportsCommand::class
]);
}
$this->app['events']->subscribe(EventHandler::class);
}
/**
* Register services.
*
* #return void
*/
public function register()
{
$this->loadRoutesFrom(__DIR__.'/routes.php');
$this->loadMigrationsFrom(__DIR__.'/database/migrations');
$this->app->singleton('convirza', function(Container $app) {
$config = config('convirza.client');
$config = Config::create($config);
return new Convirza($config);
});
$this->app->bind(ReportBuilder::class, function(Container $app) {
return new ReportBuilder($app->get('convirza'));
});
$this->app->alias('convirza', Convirza::class);
}
}
I suggest using Bugsnag's registerCallback to inspect the report and add metadata based on specific parameters of the report.
For example, you can get the context of your exception and even the stacktrace information. Additionally, you can access the originalError to get information including the error message. Using that, you can create logic in a callback to add metadata.
E.g.
public function boot()
{
Bugsnag::registerCallback(function ($report) {
$stacktrace = $report->getStacktrace();
$frames = &$stacktrace->getFrames();
// Adds metadata for `log_error` frame if present
if ($frames[0]['method'] == 'log_error') {
$report->setMetaData([
'account' => [
'token' => '12345',
]
}
]);
}

Best practice for adding custom logic in Lumen/Laravel controller

I'm using Lumen (Laravel) to create an API for an online activity/campaign application which handles things like on-site registrations and gift redemptions for various events. Occasionally, there are certain events with very specific functionality required which need their own custom logic. I'm wondering how to best handle this custom code from an architecture/best practices standpoint.
Here's what I have: I have a route which calls a CustomCampaignController like so:
$router->group([
'prefix' => 'v1'
], function () use ($router) {
// ..... other routes for standard activities
$router->post('customCampaigns', 'CustomCampaignController#runController');
});
Under App\Http\Controllers I've opened a directory to store classes for all custom activities. The customCampaigns route takes an activityId parameter whose value matches one of the activity classes. For example if the client posts activityId="MyCustomActivity" to customCampaigns, I would instantiate the following class: App\Http\Controllers\Custom\MyExampleActivity.
// app/Http/Controllers/CampaignController.php
public function runController(Request $request) {
$className = 'App\\Http\\Controllers\\Custom\\' . $request->input('activityId');
$customController = new $className;
return $customController->run();
}
The custom controller would then do its thing and return the response
// app/Http/Controllers/Custom/MyCustomActivity.php
namespace App\Http\Controllers\Custom;
class MyCustomActivity
{
public function __construct()
{
//
}
public function run()
{
// Custom logic here
return response('Response');
}
}
Is this a good approach or could it be considered an anti-pattern? Please let me know if there is another pattern for this type of problem.
I would prefer put the custom activity as the part of url. So, you will have something like this
$router->group([
'namespace' => 'App\Http\Controllers\Custom',
'prefix' => 'v1/customCampaigns'
], function () use ($router) {
$router->post('myCustomActivity', 'MyCustomActivityController#methodName');
});
Using this format, you can map the endpoint directly into a specific controller.

How can I use Doctrine 2's console tools with dynamically generated EntityManagers?

We are using Doctrine 2 in our app, but due to our infrastructure, we do not have a static configuration for database connections. Instead, we have a collection of singletons in a service provider for each database we need to connect to, and we select a random database host for then when we connect.
Unfortunately, we are seeing some performance degradation in Doctrine's getRepository() function. I believe the issue is that Doctrine needs to generate its proxy classes at runtime (even in production) because we cannot figure out how to configure the CLI tools in order to create them at build time.
We are using the Laravel framework for the application.
Here's an example of our Laravel service provider which makes the repositories available for dependency injection.
<?php
use App\Database\Doctrine\Manager as DoctrineManager;
use Proprietary\ConnectionFactory;
use App\Database\Entities;
use App\Database\Repositories;
use App\Database\Constants\EntityConstants;
class DoctrineServiceProvider extends ServiceProvider
{
// Create a singleton for the Doctrine Manager. This class will handle entity manager generation.
$this->app->singleton(DoctrineManager::class, function ($app)
{
return new DoctrineManager(
$app->make(ConnectionFactory::class),
[
EntityConstants::ENTITY_CLASS_DATABASE1 => [app_path('Database/Entities/Database1')],
EntityConstants::ENTITY_CLASS_DATABASE2 => [app_path('Database/Entities/Database2')],
],
config('app.debug'),
$this->app->make(LoggerInterface::class)
);
});
// Register the first repository
$this->app->singleton(Repositories\Database1\RepositoryA1::class, function ($app)
{
return $app[DoctrineManager::class]
->getEntityManager(EntityConstants::ENTITY_CLASS_DATABASE1)
->getRepository(Entities\Database1\RepositoryA1::class);
});
// Register the second repository
$this->app->singleton(Repositories\Database1\RepositoryA2::class, function ($app)
{
return $app[DoctrineManager::class]
->getEntityManager(EntityConstants::ENTITY_CLASS_DATABASE1)
->getRepository(Entities\Database1\RepositoryA2::class);
});
// Register a repository for the second database
$this->app->singleton(Repositories\Database2\RepositoryB1::class, function ($app)
{
return $app[DoctrineManager::class]
->getEntityManager(EntityConstants::ENTITY_CLASS_DATABASE2)
->getRepository(Entities\Database2\RepositoryB1::class);
});
}
Here's the class that generates EntityManagers for Doctrine:
<?php
use Doctrine\ORM\Tools\Setup;
use Doctrine\ORM\EntityManager;
use Doctrine\DBAL\DriverManager;
use Doctrine\DBAL\Connections\MasterSlaveConnection;
use Proprietary\ConnectionFactory;
class Manager
{
private $c_factory;
private $paths;
private $connections = [];
private $entity_managers = [];
public function __construct(
ConnectionFactory $cf,
array $paths
)
{
$this->c_factory = $cf;
$this->paths = $paths;
}
public function getConnection($name, $partition = false, $region = false)
{
// Get a list of servers for this database and format them for use with Doctrine
$servers = self::formatServers($name, $this->c_factory->getServers($name, true, $partition, $region));
// Generate a connection for the entity manager using the servers we have.
$connection = DriverManager::getConnection(
array_merge([
'wrapperClass' => MasterSlaveConnection::class,
'driver' => 'pdo_mysql',
], $servers)
);
return $connection;
}
public function getEntityManager($name, $partition = false, $region = false)
{
// Should these things be cached somehow at build time?
$config = Setup::createAnnotationMetadataConfiguration($this->paths[$name], false);
$config->setAutoGenerateProxyClasses(true);
// Set up the connection
$connection = $this->getConnection($name, $partition, $region);
$entity_manager = EntityManager::create($connection, $config);
return $entity_manager;
}
// Converts servers from a format provided by our proprietary code to a format Doctrine can use.
private static function formatServers($db_name, array $servers)
{
$doctrine_servers = [
'slaves' => [],
];
foreach ($servers as $server)
{
// Format for Doctrine
$server = [
'user' => $server['username'],
'password' => $server['password'],
'host' => $server['hostname'],
'dbname' => $db_name,
'charset' => 'utf8',
];
// Masters can also be used as slaves.
$doctrine_servers['slaves'][] = $server;
// Servers are ordered by which is closest, and Doctrine only allows a
// single master, so if we already set one, don't overwrite it.
if ($server['is_master'] && !isset($doctrine_servers['master']))
{
$doctrine_servers['master'] = $server;
}
}
return $doctrine_servers;
}
}
Our service classes use dependency injection to get the repository singletons defined in the service provider. When we use the singletons for the first time, Doctrine will use the entity class defined in the service provider and get the connection associated with the repository.
Is there any way we can enable the CLI tools with this configuration? Are there any other ways that we can optimize this for use in production?
Thanks.
I was able to solve the problem thanks to a suggestion from the Doctrine IRC channel. Since the CLI tools can only handle a single database, I created a doctrine-cli directory containing a base-config.php file and a subdirectory for each of the databases we use.
Here's an example file structure:
doctrine-cli/
|- database1/
| |- cli-config.php
|- database2/
| |- cli-config.php
|- base-config.php
The base-config.php file looks like this:
<?php
use Symfony\Component\Console\Helper\HelperSet;
use Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper;
use Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper;
use App\Database\Doctrine\Manager as DoctrineManager;
use Proprietary\ConnectionFactory;
require __DIR__ . '/../bootstrap/autoload.php';
class DoctrineCLIBaseConfig
{
private $helper_set;
public function __construct($entity_constant, $entity_namespace)
{
$app = require_once __DIR__ . '/../bootstrap/app.php';
// Proprietary factory for getting our databse details
$connection_factory = new ConnectionFactory(...);
// Our class that parses the results from above and handles our Doctrine connection.
$manager = new DoctrineManager(
$connection_factory,
[$entity_constant => [app_path('Database/Entities/' . $entity_namespace)]],
false,
null,
null
);
$em = $manager->getEntityManager($entity_constant);
$this->helper_set = new HelperSet([
'db' => new ConnectionHelper($em->getConnection()),
'em' => new EntityManagerHelper($em),
]);
}
public function getHelperSet()
{
return $this->helper_set;
}
}
Here's an example cli-config.php from the database directory:
<?php
use App\Database\Constants\EntityConstants;
require __DIR__ . "/../base-config.php";
$config = new DoctrineCLIBaseConfig(
EntityConstants::ENTITY_CLASS_DATABASE1,
"database1"
);
return $config->getHelperSet();
Now, I'm able to cycle through each of the directories and run commands like so:
php ../../vendor/bin/doctrine orm:generate-proxies
For our build process, I wrote a simple shell script that cycles through the directories and runs the orm:generate-proxies command.

ZF2 Unit test of login in wierd code

I am new to ZF2 and I want to test the login method in a legacy application. Or introduce Unit tests in old code :).
The code that I have is not done according to the manual; it seems super strange if I compare it to the manual examples or even best practices.
I the login method like this:
http://pastebin.com/ZzvuBcGe
in this case the legacy is that Helper, Carts, Users, Userslogs and Usertests are models .... all of them extend DB.
In the module.config.php I have this code:
'service_manager' => array(
'factories' => array(
'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory',
'AuthService' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$dbTableAuthAdapter = new DbTableAuthAdapter(
$dbAdapter,
'tbl_user',
'USER_LOGIN',
'USER_PASSWORD',
'MD5(?)'
);
$authService = new AuthenticationService();
$authService->setAdapter($dbTableAuthAdapter);
$authService->setStorage(new StorageSession('session'));
return $authService;
},
'Helper' => function ($sm) {
return new Helper($sm);
},
'Users' => function ($sm) {
return new Users($sm);
},
'Carts' => function ($sm) {
return new Carts($sm);
}
...
I know that the DbTableAuthAdapter is deprecated but I have to understand how to modify this in order to change it in the best way possible. I have the feeling if I change this all the User, Carts etc models will crash.
My Unit test is like this for the moment:
<?php namespace ApplicationTest\Controller;
use Application\Controller\LoginController;
use Zend\Stdlib\ArrayUtils;
use Zend\Test\PHPUnit\Controller\AbstractHttpControllerTestCase;
class LoginControllerTest extends AbstractHttpControllerTestCase
{
protected $traceError = true;
public function setUp()
{
parent::setUp();
// The module configuration should still be applicable for tests.
// You can override configuration here with test case specific values,
// such as sample view templates, path stacks, module_listener_options,
// etc.
$configOverrides = [];
$this->setApplicationConfig(ArrayUtils::merge(
// Grabbing the full application configuration:
include __DIR__ . '/../../../../../config/application.config.php',
$configOverrides
));
}
public function loginCredentialsProvider()
{
return [
['userDev', '12345'],
];
}
/**
* #covers LoginController::loginAction()
* #dataProvider loginCredentialsProvider
* #param $username
* #param $password
*/
public function testLogin($username, $password)
{
// prepare request
//$this->getRequest()
//->setMethod('POST')
//->setPost(new Parameters(array(
//'user_login' => $username,
//'user_password' => $password
//)));
$helperMock = $this->getMockBuilder('Application\Model\Helper')
->disableOriginalConstructor()
->getMock();
$serviceManager = $this->getApplicationServiceLocator();
$serviceManager->setAllowOverride(true);
$serviceManager->setService('Application\Model\Helper', $helperMock);
// send request
$this->dispatch('/login', 'POST', $this->loginCredentialsProvider());
$this->assertEquals('userDev12345', $username . $password);
// $this->markTestIncomplete('login incomplete');
}
/**
* #depends testLogin
*/
public function testLogout()
{
$this->markTestIncomplete('logout incomplete');
}
}
I tried different ways to test but no succes and of course that I get errors:
Zend\ServiceManager\Exception\ServiceNotCreatedException: An exception was raised while creating "Helper"; no instance returned
/project/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php:930
/project/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php:1057
/project/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php:633
/project/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php:593
/project/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php:525
/project/module/Application/src/Application/Controller/LoginController.php:38
/project/vendor/zendframework/zendframework/library/Zend/Mvc/Controller/AbstractActionController.php:83
/project/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php:468
/project/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php:207
/project/vendor/zendframework/zendframework/library/Zend/Mvc/Controller/AbstractController.php:116
/project/vendor/zendframework/zendframework/library/Zend/Mvc/DispatchListener.php:113
/project/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php:468
/project/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php:207
/project/vendor/zendframework/zendframework/library/Zend/Mvc/Application.php:313
/project/vendor/zendframework/zendframework/library/Zend/Test/PHPUnit/Controller/AbstractControllerTestCase.php:282
/project/module/Application/test/ApplicationTest/Controller/LoginControllerTest.php:69
/project/vendor/phpunit/phpunit/phpunit:47
Caused by
Zend\ServiceManager\Exception\ServiceNotCreatedException: An exception was raised while creating "Zend\Db\Adapter\Adapter"; no instance returned
/project/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php:930
/project/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php:1055
/project/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php:633
/project/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php:593
/project/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php:525
/project/module/Application/src/Application/Model/DB.php:17
/project/module/Application/config/module.config.php:1324
/project/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php:923
/project/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php:1057
/project/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php:633
/project/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php:593
/project/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php:525
/project/module/Application/src/Application/Controller/LoginController.php:38
/project/vendor/zendframework/zendframework/library/Zend/Mvc/Controller/AbstractActionController.php:83
/project/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php:468
/project/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php:207
/project/vendor/zendframework/zendframework/library/Zend/Mvc/Controller/AbstractController.php:116
/project/vendor/zendframework/zendframework/library/Zend/Mvc/DispatchListener.php:113
/project/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php:468
/project/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php:207
/project/vendor/zendframework/zendframework/library/Zend/Mvc/Application.php:313
/project/vendor/zendframework/zendframework/library/Zend/Test/PHPUnit/Controller/AbstractControllerTestCase.php:282
/project/module/Application/test/ApplicationTest/Controller/LoginControllerTest.php:69
/project/vendor/phpunit/phpunit/phpunit:47
Caused by
PHPUnit_Framework_Error_Notice: Undefined index: db
/project/vendor/zendframework/zendframework/library/Zend/Db/Adapter/AdapterServiceFactory.php:26
/project/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php:923
/project/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php:1055
/project/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php:633
/project/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php:593
/project/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php:525
/project/module/Application/src/Application/Model/DB.php:17
/project/module/Application/config/module.config.php:1324
/project/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php:923
/project/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php:1057
/project/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php:633
/project/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php:593
/project/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php:525
/project/module/Application/src/Application/Controller/LoginController.php:38
/project/vendor/zendframework/zendframework/library/Zend/Mvc/Controller/AbstractActionController.php:83
/project/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php:468
/project/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php:207
/project/vendor/zendframework/zendframework/library/Zend/Mvc/Controller/AbstractController.php:116
/project/vendor/zendframework/zendframework/library/Zend/Mvc/DispatchListener.php:113
/project/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php:468
/project/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php:207
/project/vendor/zendframework/zendframework/library/Zend/Mvc/Application.php:313
/project/vendor/zendframework/zendframework/library/Zend/Test/PHPUnit/Controller/AbstractControllerTestCase.php:282
/project/module/Application/test/ApplicationTest/Controller/LoginControllerTest.php:69
/project/vendor/phpunit/phpunit/phpunit:47
The issues that I have are first how to get the test to pass with this code? I know that normally you do the test and after that the code but I need a starting point to understand the mess that I have in the application. Second, what is the easy or the best way to modify the "models" to not be a dependency for each method and then pass the test? How to modify the deprecated DbTableAuthAdapter in order not to brake all things?
Like i said I am new to ZF2 and Phpunit and I am stuck over this messy code and I have the best practices in my mind but I don't know how to put them in action in this code. Thank you for all the info that I will receive for this.
LATER EDIT
the solution is to add this line in the test, foreach model:
// access via application object..
$bla = $this->getApplication()->getServiceManager()->get('Tests');
the solution is to add this line in the test, foreach model:
$bla = $this->getApplication()->getServiceManager()->get('Tests');
Thank you i336_ :)

ding integration with zend framework

We're using ZendFramework at my workplace for our webapps. It's ok, but it lacks some of the best modern practices (like dependency injection and inversion of control, aop, etc).
For a couple of months, I've been (on my own) using Ding framework as a container for DI and AOP as a test drive. I really like it, so I'd like to bring it into our projects.
But how? So there's the question: how to properly integrate Ding in Zend Framework applications? considering ZF controllers cant be beans (as they are instantiated right from the dispatcher), how to propertly inject all dependencies in them?
P.s: Not using Zend Framework is not an option (at least in the middle term).
P.P.S: Anyone care to add "ding" as a new tag?
I'm glad Ding is helping you.
I contributed on this project and also needed to integrate with a Zend Framework application. I used Zend's application resources and plugin system to achieve this.
An application resource (you can reuse among projects)
<?php
class Application_Resource_Ding extends Zend_Application_Resource_ResourceAbstract
{
protected $_options = array(
'factory' => array(
'bdef' => array(
'xml' => array(
'filename' => array('beans.xml')
),
),
),
'cache' => array(
'proxy' => array('impl' => 'dummy'),
'bdef' => array('impl' => 'dummy'),
'beans' => array('impl' => 'dummy')
)
);
public function init()
{
// set default config dir before mergin options (cant be set statically)
$this->_options['factory']['bdef']['xml']['directories'] = array(APPLICATION_PATH .'/configs');
$options = $this->getOptions();
// parse factory properties (if set)
if (isset($options['factory']['properties'])) {
$options['factory']['properties'] = parse_ini_file(
$options['factory']['properties']
);
}
// change log4php_properties for log4php.properties (if exists)
if (isset($options['log4php_properties'])) {
$options['log4php.properties'] = $options['log4php_properties'];
unset($options['log4php_properties']);
}
$properties = array(
'ding' => $options
);
return Ding\Container\Impl\ContainerImpl::getInstance($properties);
}
}
An action helper to use inside the controllers:
<?php
class Application_Action_Helper_Ding extends Zend_Controller_Action_Helper_Abstract
{
protected $ding = null;
public function init()
{
// just once...
if (null !== $this->ding) {
return;
}
// get ding bootstrapped resource
$bootstrap = $this->getActionController()->getInvokeArg('bootstrap');
$ding = $bootstrap->getResource('ding');
if (!$ding) {
throw new Zend_Controller_Action_Exception(
'Ding resource not bootstrapped'
);
}
$this->ding = $ding;
}
public function getBean($bean)
{
return $this->ding->getBean($bean);
}
public function direct($bean)
{
return $this->getBean($bean);
}
}
In your application.ini you should add something like this (plus any extra configuration you need)
resources.frontController.actionHelperPaths.Application_Action_Helper = "Application/Action/Helper"
resources.ding.factory.properties = APPLICATION_PATH "/configs/ding.properties"
resources.ding.log4php_properties = APPLICATION_PATH "/configs/log4php.properties"
And then in your controllers, to request a bean:
$service = $this->_helper->ding('someService');
Hope this helps!

Categories