Thus far I've been testing my ZF2 controllers as follows:
namespace Application\Controller;
use Application\Controller\IndexController;
use Zend\Http\Request;
use Zend\Http\Response;
use Zend\Mvc\MvcEvent;
use Zend\Mvc\Router\RouteMatch;
use PHPUnit_Framework_TestCase;
class IndexControllerTest extends PHPUnit_Framework_TestCase
{
public function testIndexActionCanBeAccessed()
{
$this->routeMatch->setParam('action', 'index');
$result = $this->controller->dispatch($this->request);
$response = $this->controller->getResponse();
$this->assertEquals(200, $response->getStatusCode());
$this->assertInstanceOf('Zend\View\Model\ViewModel', $result);
}
protected function setUp()
{
\Zend\Mvc\Application::init(include 'config/application.config.php');
$this->controller = new IndexController();
$this->request = new Request();
$this->routeMatch = new RouteMatch(array('controller' => 'index'));
$this->event = new MvcEvent();
$this->event->setRouteMatch($this->routeMatch);
$this->controller->setEvent($this->event);
}
protected $controller = null;
protected $event = null;
protected $request = null;
protected $response = null;
protected $routeMatch = null;
}
This allows me to test that the ViewModel is having the correct data (if any) assigned to it before the view is rendered. This serves that purpose just fine, but what it doesn't do is test that my routing is working correctly like the ZF1 Zend_Test_PHPUnit_Controller_TestCase tests would.
In those, I'd kick off the test by running $this->dispatch('/some/relative/url') and only get positive test results if the routes were set up correctly. With these ZF2 tests, I'm specifically telling it which route to use, which doesn't necessarily mean that a real request will be routed correctly.
How do I test that my routing is working correctly in ZF2?
I'm late to the party, but it still could be useful for newcomers. The solution nowadays would be to inherit from \Zend\Test\PHPUnit\Controller\AbstractControllerTestCase, so the usage would be very similar to ZF1:
class IndexControllerTest extends \Zend\Test\PHPUnit\Controller\AbstractHttpControllerTestCase
{
public function setUp()
{
$this->setApplicationConfig(
include __DIR__ . '/../../../../../config/application.config.php'
);
parent::setUp();
}
public function testIndexActionCanBeAccessed()
{
$this->dispatch('/');
$this->assertResponseStatusCode(200);
$this->assertModuleName('application');
$this->assertControllerName('application\controller\index');
$this->assertControllerClass('IndexController');
$this->assertMatchedRouteName('home');
$this->assertQuery('html > head');
}
}
Note: This uses \Zend\Test\PHPUnit\Controller\AbstractHttpControllerTestCase which includes assertQuery($path) as well as other web related methods.
EDIT: ZF2 has been updated since I self-answered this. PowerKiki's answer is better.
Related
I have created a simple aplication in Silex 1.3.4 and I want to have a base controller that will have a __construct method accepting $app and $request. All inheriting controllers then should have their respective constructors and calling the parent controller construct method.
//Use statements here....
class AppController
{
public function __construct(Application $app, Request $request){
$this->app = $app;
$this->request = $request;
}
}
Inheriting controllers would be written as below:
//Use statements here....
class ItemsController extends AppController
{
public function __construct(Application $app, Request $request){
parent::__construct($app, $request);
}
public function listAction()
{
//code here without having to pass the application and request objects
}
}
The approach I have decided on routing is as shown below:
$app->post(
'/items/list', 'MySilexTestDrive\Controller\ItemsController::listAction'
)->bind('list');
I was thinking of using the dispatcher and override some processes there and create my controller instances my own way but I do not have any idea how and if this is a great idea at all.
Anyone who has done something similar to this? Please help.
You can use ServiceControllerServiceProvider to define your controller as a service in the application. But you can't inject a Request in that way. BTW you can have more than one request and the request instance can change if you do sub-request. You can inject RequestStack instead, then call $requestStack->getCurrentRequest() when you need to get the current request.
$app = new Silex\Application();
abstract class AppController
{
protected $app;
protected $requestStack;
public function __construct(Silex\Application $app, Symfony\Component\HttpFoundation\RequestStack $requestStack)
{
$this->app = $app;
$this->requestStack = $requestStack;
}
public function getRequest()
{
return $this->requestStack->getCurrentRequest();
}
}
class ItemsController extends AppController
{
public function listAction()
{
$request = $this->getRequest();
// ...
}
}
$app->register(new Silex\Provider\ServiceControllerServiceProvider());
$app['items.controller'] = $app->share(function() use ($app) {
return new ItemsController($app, $app['request_stack']);
});
$app->get('/items/list', "items.controller:listAction");
It makes sense to do such a thing? I do not think so. Especially if the framework gives you a request instance thanks to the type hinting. Just do
public function listAction(Application $app, Request $request)
{
// ...
}
and work with that.
You can try this too :
class BaseController
{
protected $app;
protected $request;
public function __call($name, $arguments)
{
$this->app = $arguments[0];
$this->request = $arguments[1];
return call_user_func_array(array($this,$name), [$arguments[0], $arguments[1]]);
}
protected function getSystemStatus(Application $app, Request $request)
{
[...]
}
[...]
}
#Rabbis and #Federico I have come up with a more elegant solution for this where I have created a BeforeControllerExecuteListener that I dispatch with my application instance. This listener accepts the FilterControllerEvent object and then from my base controller I call a method where I inject both the Silex Application and the request from the event.
public function onKernelController(FilterControllerEvent $event)
{
$collection = $event->getController();
$controller = $collection[0];
if($controller instanceof BaseControllerAwareInterface){
$controller->initialize($this->app, $event->getRequest());
}
}
The I simple dispatch this in my bootstrap file as shown below:
$app['dispatcher']->addSubscriber(new BeforeControllerExecuteListener($app));
This allows me to have access to this object without having to add them as parameters on my actions. Below is how one of my actions in the making looks:
public function listAction($customer)
{
$connection = $this->getApplication()['dbs']['db_orders'];
$orders= $connection->fetchAll($sqlQuery);
$results = array();
foreach($orders as $order){
$results[$order['id']] = $order['number'] . ' (' . $order['customer'] . ')';
}
return new JsonResponse($results);
}
If the currently running controller being called honors the BaseControllerAwareInterface interface as I have defined it then it means I should inject that controller with the Application and Request instances. I leave the controllers to deal with how they manage the Response of each action as with my example above I may need the Response object itself of JsonResponse even any other type of response so it entirely depends on the controller to take care of that.
Then the routing remains as simply as:
$app->match('/orders/list/{cusstomer}', 'Luyanda\Controller\OrdersController::listAction')
->bind('list-orders');
Im having trouble understanding how to access the instance of Slim when a route is in a seperate class than index.php
When using Slim Framework 2 I always used the following, but its not working in Slim 3:
$this->app = \Slim\Slim::getInstance();
Im trying to access a database connection I have setup in the container, but from a separate class. This is what I currently got in my index.php to initiate a Slim app:
require_once("rdb/rdb.php");
$conn = r\connect('localhost');
$container = new \Slim\Container;
$container['rdb'] = function ($c){return $conn;}
$app = new \Slim\App($container);
And here is my route:
$app->get('/test','\mycontroller:test');
And this is what I got in my mycontroller.php class which my route points to, which obviously is not working as $this->app doesn't exist:
class mycontroller{
public function test($request,$response){
$this->app->getContainer()->get('rdb');
}
The error message is the following, due to getinstance not being part of Slim 3 compared to Slim 2:
Call to undefined method Slim\App::getInstance()
Grateful for any help,
Regards
Dan
Have a look at the Slim 3 Skeleton created by Rob Allen.
Slim 3 heavily uses dependency injection, so you might want to use it too.
In your dependencies.php add something like:
$container = $app->getContainer();
$container['rdb'] = function ($c) {
return $conn;
};
$container['Your\Custom\Class'] = function ($c) {
return new \Your\Custom\Class($c['rdb']);
};
And in your Your\Custom\Class.php:
class Class {
private $rdb;
function __construct($rdb) {
$this->rdb = $rdb;
}
public function test($request, $response, $args) {
$this->rdb->doSomething();
}
}
I hope this helps, if you have any more questions feel free to ask.
Update:
When you define your route like this
$app->get('/test', '\mycontroller:test');
Slim looks up \mycontroller:test in your container:
$container['\mycontroller'] = function($c) {
return new \mycontroller($c['rdb']);
}
So when you open www.example.com/test in your browser, Slim automatically creates a new instance of \mycontroller and executes the method test with the arguments $request, $response and $args.
And because you accept the database connection as an argument for the constructor of your mycontroller class, you can use it in the method as well :)
With Slim 3 RC2 and onwards given a route of:
$app->get('/test','MyController:test');
The CallableResolver will look for a key in the DIC called 'MyController' and expect that to return the controller, so you can register with the DIC like this:
// Register controller with DIC
$container = $app->getContainer();
$container['MyController'] = function ($c) {
return new MyController($c->get('rdb'));
}
// Define controller as:
class MyController
{
public function __construct($rdb) {
$this->rdb = $rdb;
}
public function test($request,$response){
// do something with $this->rdb
}
}
Alternatively, if you don't register with the DIC, then the CallableResolver will pass the container to your constructor, so you can just create a controller like this:
class MyController
{
public function __construct($container) {
$this->rdb = $container->get('rdb');
}
public function test($request,$response){
// do something with $this->rdb
}
}
I created the following base controller and extended from that. Only just started playing with Slim but it works if you need access to to the DI in your controllers.
namespace App\Controllers;
use Interop\Container\ContainerInterface;
abstract class Controller
{
protected $ci;
/**
* Controller constructor.
*
* #param ContainerInterface $container
*/
public function __construct(ContainerInterface $container)
{
$this->ci = $container;
}
/**
* #param $name
* #return mixed
*/
public function __get($name)
{
if ($this->ci->has($name)) {
return $this->ci->get($name);
}
}
}
Then in your other controllers you can use it like this.
namespace App\Controllers;
/**
* Class HomeController
*
* #package App\Controllers
*/
class HomeController extends Controller
{
/**
* #param $request
* #param $response
* #param $args
* #return \Slim\Views\Twig
*/
public function index($request, $response, $args)
{
// Render index view
return $this->view->render($response, 'index.twig');
}
}
Important
I upvoted #mgansler and you should read that first if dealing with slim 3, and read this only if interested in differences to slim 2.
Update
So it seems those usages were just old code no one cleaned.
However im leaving this post here as it should be helpful to anyone using Slim 2 (as slim 3 is very much still beta) and as a referance point to help see differences.
Old Update (see above)
Following update of OP, i looked at github source code and found that getInstance is still very much there, but with some slight differences perhaps...
https://github.com/slimphp/Slim/search?utf8=%E2%9C%93&q=getInstance
Test files (which maybe outdated, but unlikely) show something like this:
public function testGetCallableAsStaticMethod()
{
$route = new \Slim\Route('/bar', '\Slim\Slim::getInstance');
$callable = $route->getCallable();
$this->assertEquals('\Slim\Slim::getInstance', $callable);
}
But at the same time we see calls like this in some files, which are obviously contextual and either return diff object ($env) or are in same static file (Slim.php)
$env = \Slim\Environment::getInstance(true);
static::getInstance();
But this does show the static function still exists, so use my examples below and try to figure out why not working for you in current form.
Also, this 'maybe' of interest, as only obvious example of slim3 in usage: https://github.com/akrabat/slim3-skeleton
Though other projects prob exist, search with github filters if still having issues.
Original Answer content
Please include more detail on the route and the other class, but here are 3 ways, with execution examples detailed further down.
This info does relate to Slim Framework 2, not the Slim 3 beta, but slim 3 beta shows similar example code and makes no mention of overhauling changes, and in fact links to the Slim 2 documentation: http://docs.slimframework.com/configuration/names-and-scopes/
$this->app->getContainer()->get('rdb');
// Recommended approach, can be used in any file loaded via route() or include()
$app = \Slim\Slim::getInstance();
Slim::getInstance();
App::config('filename');
Slim3 Beta has only one code example, which looks like this:
$app = new \Slim\App();
// which would by extension mean that this 'might' work too
$app = \Slim\App::getInstance();
// but be sure to try with slim2 naming just in case
$app = \Slim\Slim::getInstance()
Though obviously this doesnt fit outside of index.php, but is consistent with Slim2 doco showing GetInstance works.
Which one fits you?
I have multiple files that use these different approaches, though i cant say what fits best as too little context on how this external class fits in and what its composition is.
For example, my controllers (which are endpoints of most my routes) use the same approach, through a base class or just direct:
class ApiBaseController /// extends \BaseController
{
protected $app;
protected $data;
public function __construct()
{
$this->app = Slim\Slim::getInstance();
$this->data = array();
}
//...
}
class VideoApiController extends \ApiBaseController
{
// ...
public function embed($uid)
{
// trace($this->app->response->headers());
$vid = \R::findOne('videos'," uid = ? ",array($uid));
if(!empty($vid))
{
// embed logic
}else{
// see my baseclass
$this->app->render('api/404.html', array(), 404);
}
}
// ...
// Returns the video file, keeping actual location obscured
function video($uid)
{
require_once(APP_PATH.'helpers/player_helper.php');
$data = \R::findOne('videos'," uid = ? ",array($uid));
/// trace($_SERVER); die();
if($data)
{
stream_file($data['filename']);
}else{
$app = \Slim\Slim::getInstance();
$app->render('404.html');
}
/// NOTE - only same domain for direct /v/:uid call
header('Access-Control-Allow-Origin : '.$_SERVER['HTTP_HOST']);
// header('X-Frame-Options: SAMEORIGIN');
// Exit to be certain nothing else returned
exit();
}
//...
}
My helper files show code like this:
function get_permissions_options_list($context = null)
{
if(empty($context)) $context = 'user';
return App::config('permissions')[$context];
}
My middleware:
function checkAdminRoutePermissions($route)
{
$passed = runAdminRoutePermissionsCheck($route);
if($passed)
return true;
// App::notFound();
// App::halt(403, $route->getPattern());
if(!Sentry::check())
App::unauthorizedNoLogin();
else
App::unauthorized();
return false;
}
Thats example of how i access in the various files, though the code you shared already shows that you have used the recommended approach already
$app = \Slim\Slim::getInstance();
Though again, need more info to say for sure how your external file fits in, but if its at the end of a route or in an 'include()', then it should work.
You said your old approach didnt work though, but gave no info on what the actual result vs expected result was (error msg, ect), so if this doesnt work please update the OP.
This was a tough one. #mgansler answer was really helpful, but in his answer he passed a database connection, and not exactly $app inside the controller
Following the same idea it is possible to send $app though.
First inside your dependencies.php you need to grab the $app and throw it in a container to inject it to the Controller later.
$container['slim'] = function ($c) {
global $app;
return $app;
};
Then you got to inject it:
// Generic Controller
$container['App\Controllers\_Controller'] = function ($c) {
return new _Controller($c->get('slim'));
};
Now on your controller.php:
private $slim;
/**
* #param \Psr\Log\LoggerInterface $logger
* #param \App\DataAccess $dataaccess
* #param \App\$app $slim
*/
public function __construct(LoggerInterface $logger, _DataAccess $dataaccess, $slim)
{
$this->logger = $logger;
$this->dataaccess = $dataaccess;
$this->slim = $slim;
}
Now you just got call it like this:
$this->slim->doSomething();
I'm trying to achieve generated routes in my functional tests. I want them to be generated dynamically,preferably by name, but I cannot find a proper way how to do it. Point me please.
A simple test:
public function testIndex()
{
// I have service container
$container = $this->client->getContainer();
$crawler = $client->request('GET', helper_function("route_name", $params));
$heading = $crawler->filter('h1')->eq(0)->text();
$this->assertEquals('Application list', $heading);
}
What that helper_function() should be?
Since you have access to service container you can get router (which by default will return Symfony\Component\Routing) service and call generate method on it.
$route = $container->get('router')->generate($routeName, $params);
In the setup of the WebTestCase class you can take an instance of the router component then use it as usually.
As Example:
class AcmeDemoTestCase extends WebTestCase
protected $router;
protected function setUp()
{
........
$this->client = static::createClient();
$this->router = $this->client->getContainer()->get('router');
.....
}
public function testIndex()
{
$crawler = $this->client->request('GET', $this->router->generate($routeName, $params););
}
Hope this help
I use Cakephp 2.1 and I need to call a component method which resides in a plugin, from a view helper:
The component is here:
/app/Plugin/Abc/Controller/Component/AbcComponent.php
The helper is here:
/app/View/Helper/SimpleHelper.php
I tried inside helper:
App::import('Component', 'Abc.Abc');
$this->Abc = new Abc(); or $this->Abc = new AbcComponent;
or
$this->Abc = $this->Components->load('Abc.Abc');
inside the controllers this component works with no problem.
I know this isn't recommended (MVC design etc.) but if I don't use it this way I need to duplicate a lot of code. I need to make something like:
MyHelper extends Helper{
$simpleVar = Component->get_data();
}
I use CakePHP 2.4
This is how I successfully call Component from a Helper:
App::uses('AclComponent', 'Controller/Component');
class MyHelper extends AppHelper {
public function myFunction() {
$collection = new ComponentCollection();
$acl = new AclComponent($collection);
// From here you can use AclComponent in $acl
if ($acl->check($aro, $aco) {
// ...
}
}
}
Passing data from CakePHP component to a helper
This seems to be a very nice way to handle this.
I tried working the way you are before, and, although it seems to be a nice immediate solution, in the long run, it is better to just work with the component and helper as 2 separate entities in your controller.
lee
You can put logic in trait and use this from component and helper, if your porpouse is to use the same business logic in different places, to avoid duplication code.
By example
the trait (file app/Lib/NameOfTrait.php or app/PluginName/Lib/NameOfTrait.php)
trait NameOfTrait {
public function theTraitFunc($a, $b) {
// Code here
}
}
The Component:
App::uses('Component', 'Controller');
App::uses('NameOfTrait', 'PluginName.Lib');
class NameOfComponent extends Component {
use NameOfTrait;
private $member;
private $controller;
public function __construct(ComponentCollection $collection, $settings = array()) {
parent::__construct($collection, $settings);
$this->member = $settings['memberName'];
}
function startup(Controller $controller) {
$this->controller = $controller;
}
/**
* Wrap function call of trait function,
* I think the function doesn't have the same name,
* I don't try this but I think is obvious,
* to avoid the function to call itself
*/
public function theTraitFuncWrap($a) {
return $this->theTraitFunc($a, $this->member);
}
}
Do The same for the Helper.
I hope this help someone, bye :)
I've been trying to test a model in a Symfony2 project, but I don't know how to get the entity manager to save and retrive records.
Can anyone point me to the right docs for this?
In order to test your models, you can use setUp() method. link to docs
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class MyModelTest extends WebTestCase
{
/**
* #var EntityManager
*/
private $_em;
protected function setUp()
{
$kernel = static::createKernel();
$kernel->boot();
$this->_em = $kernel->getContainer()->get('doctrine.orm.entity_manager');
$this->_em->beginTransaction();
}
/**
* Rollback changes.
*/
public function tearDown()
{
$this->_em->rollback();
}
public function testSomething()
{
$user = $this->_em->getRepository('MyAppMyBundle:MyModel')->find(1);
}
Hope this helps you
Symfony2 models are expected to be domain objects that represent domain models in the code.
domain objects should be defined purely to implement the business
behavior of the corresponding domain concept, rather than be defined
by the requirements of a more specific technology framework. -- Domain-driven design - Wikipedia, the free encyclopedia
Domain objects (and its tests) should not depend on Symfony2 APIs and Doctrine APIs except if you really want to test themselves.
Writing Symfony2 unit tests is no different than writing standard PHPUnit unit tests. -- Symfony - Testing
You can test business logic (processes, rules, behaviors, etc.) represented in domain objects with PHPUnit (or Behat) and usually test doubles.
namespace Ibw\JobeetBundle\Tests\Repository;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Output\NullOutput;
use Symfony\Component\Console\Input\ArrayInput;
use Doctrine\Bundle\DoctrineBundle\Command\DropDatabaseDoctrineCommand;
use Doctrine\Bundle\DoctrineBundle\Command\CreateDatabaseDoctrineCommand;
use Doctrine\Bundle\DoctrineBundle\Command\Proxy\CreateSchemaDoctrineCommand;
class CategoryRepositoryTest extends WebTestCase
{
private $em;
private $application;
public function setUp()
{
static::$kernel = static::createKernel();
static::$kernel->boot();
$this->application = new Application(static::$kernel);
// drop the database
$command = new DropDatabaseDoctrineCommand();
$this->application->add($command);
$input = new ArrayInput(array(
'command' => 'doctrine:database:drop',
'--force' => true
));
$command->run($input, new NullOutput());
// we have to close the connection after dropping the database so we don't get "No database selected" error
$connection = $this->application->getKernel()->getContainer()->get('doctrine')->getConnection();
if ($connection->isConnected()) {
$connection->close();
}
// create the database
$command = new CreateDatabaseDoctrineCommand();
$this->application->add($command);
$input = new ArrayInput(array(
'command' => 'doctrine:database:create',
));
$command->run($input, new NullOutput());
// create schema
$command = new CreateSchemaDoctrineCommand();
$this->application->add($command);
$input = new ArrayInput(array(
'command' => 'doctrine:schema:create',
));
$command->run($input, new NullOutput());
// get the Entity Manager
$this->em = static::$kernel->getContainer()
->get('doctrine')
->getManager();
// load fixtures
$client = static::createClient();
$loader = new \Symfony\Bridge\Doctrine\DataFixtures\ContainerAwareLoader($client->getContainer());
$loader->loadFromDirectory(static::$kernel->locateResource('#IbwJobeetBundle/DataFixtures/ORM'));
$purger = new \Doctrine\Common\DataFixtures\Purger\ORMPurger($this->em);
$executor = new \Doctrine\Common\DataFixtures\Executor\ORMExecutor($this->em, $purger);
$executor->execute($loader->getFixtures());
}
public function testFunction()
{
// here you test save any object or test insert any object
}
protected function tearDown()
{
parent::tearDown();
$this->em->close();
}
}
like in this Link : Jobeet Unit Test Tutorial
explain how to Test Entity and Entity Repository