Set up a Zend Framework application using Zend_Application (including PHPUnit setup)

Today I spent some time setting up a new Zend Framework application using ZF 1.8.0 Beta 1 and the new component Zend_Application. Using that component, all bootstrapping is done by Zend_Application_Bootstrap and so-called resource plugins. Such resource plugins are responsible for initialization of single components such as front controller, database or the view. This way, the whole bootstrapping is nicely modularized and keeps some headache away. In addition, the majority of settings can be set in the application config file. As I ran into some issues, I’d like to note the required steps and hope that it’s useful so someone. I won’t explain the files in detail, you can find enough information about components and parameters on the manual and the quickstart, but you should get to a working setup with just copy&pasting the code here ;)

Basically a big part of this setup can be done using the new Zend_Tool CLI, however I had some problems setting it up, so I’ve done it manually (however most of the code is the one generated by Zend_Tool).

At first, let’s create the directory structure:

mkdir -p public/css
mkdir -p public/img
mkdir -p public/js
mkdir -p application/configs
mkdir -p application/controllers
mkdir -p application/layouts/scripts
mkdir -p application/models
mkdir -p application/views/helpers
mkdir -p application/views/scripts/index
mkdir -p application/views/scripts/error
mkdir -p data/session
mkdir -p bin
mkdir -p library/App
mkdir -p tests/application
mkdir -p tests/application/controllers

Download the ZF release and drop the Zend directory into library. Now we’re ready to go.

Public files

public/.htaccess

SetEnv APPLICATION_ENV development

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]

public/index.php just sets needed path and environment constants and lets Zend_Application do the rest. As I mentioned before, most of the settings are set in the application config file.

<?php
define('BASE_PATH', realpath(dirname(__FILE__) . '/../'));
define('APPLICATION_PATH', BASE_PATH . '/application');

// Include path
set_include_path(
    BASE_PATH . '/library'
    . PATH_SEPARATOR . get_include_path()
);

// Define application environment
defined('APPLICATION_ENV')
    || define('APPLICATION_ENV',
              (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV')
                                         : 'production'));

// Zend_Application
require_once 'Zend/Application.php';

$application = new Zend_Application(
    APPLICATION_ENV,
    APPLICATION_PATH . '/configs/application.ini'   
);

$application->bootstrap();
$application->run();

Config file

application/configs/application.ini: In my setup I got 3 databases for development, testing and production, so the DB definitions differ between environments.

[production]

# Debug output
phpSettings.display_startup_errors = 0
phpSettings.display_errors = 0

# Include path
includePaths.library = APPLICATION_PATH "/../library"

# Bootstrap
bootstrap.path = APPLICATION_PATH "/Bootstrap.php"
bootstrap.class = "Bootstrap"

# Front Controller
resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers"
resources.frontController.env = APPLICATION_ENV

# Layout
resources.layout.layout = "layout"
resources.layout.layoutPath = APPLICATION_PATH "/layouts/scripts"

# Views
resources.view.encoding = "UTF-8"
resources.view.basePath = APPLICATION_PATH "/views/"

# Database
resources.db.adapter = "pdo_mysql"
resources.db.params.host = "localhost"
resources.db.params.username = "myproject"
resources.db.params.password = "myproject"
resources.db.params.dbname = "myproject_production"
resources.db.isDefaultTableAdapter = true

# Session
resources.session.save_path = APPLICATION_PATH "/../data/session"
resources.session.remember_me_seconds = 864000

[testing : production]

# Debug output
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1

# Database
resources.db.params.dbname = "myproject_testing"

[development : production]

# Debug output
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1

# Database
resources.db.params.dbname = "myproject_development"

Bootstrap

application/Bootstrap.php: as defined in the config file, the application uses this file for the bootstrap process. I let Zend_Application handle all necessary initialization except the view. This was mainly because I wanted to set the view doctype to XHTML.

<?php
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
    protected function _initView()
    {
        // Initialize view
        $view = new Zend_View();
        $view->doctype('XHTML1_STRICT');
        $view->headTitle('My Project');
        $view->env = APPLICATION_ENV;

        // Add it to the ViewRenderer
        $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper(
            'ViewRenderer'
        );
        $viewRenderer->setView($view);

        // Return it, so that it can be stored by the bootstrap
        return $view;
    }
}

Done. That was the whole bootstrapping process. Your application is now ready to use ZF’s MVC implementation + Database. So let’s continue to add Application specific elements.

Add a layout

Let’s add a basic layout in application/layouts/scripts/layout.phtml:

<?php echo $this->doctype() ?>
<html>
<head>
    <?php echo $this->headTitle() ?>
    <?php echo $this->headLink() ?>
    <?php echo $this->headStyle() ?>
    <?php echo $this->headScript() ?>
</head>
<body>
    <?php echo $this->layout()->content ?>
</body>
</html>

Add Controllers and views

application/controllers/IndexController.php: nothing special here.

<?php
class IndexController extends Zend_Controller_Action
{
    public function indexAction()
    {
    }
}

And the view for index/index in application/views/scripts/index/index.phtml

<h1>Welcome to the Zend Framework!</h1>

application/controllers/ErrorController.php: is called in case of an error (e.g. controller does not exist). Depending on your environment it shows the exception and stack trace.

<?php
class ErrorController extends Zend_Controller_Action
{
    public function errorAction()
    {
        $errors = $this->_getParam('error_handler');

        switch ($errors->type) { 
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:

                // 404 error -- controller or action not found
                $this->getResponse()->setHttpResponseCode(404);
                $this->view->message = 'Page not found';
                break;
            default:
                // application error 
                $this->getResponse()->setHttpResponseCode(500);
                $this->view->message = 'Application error';
                break;
        }

        $this->view->exception = $errors->exception;
        $this->view->request   = $errors->request;
    }
}

And the belonging view in application/views/scripts/error/error.phtml.

<h1>An error occurred</h1> 
<h3><?php echo $this->message ?></h3> 

<? if ('development' == $this->env): ?> 

    <h4>Exception information:</h4> 
    <p> 
      <strong>Message:</strong> <?php echo $this->exception->getMessage(); ?> 
    </p> 

    <h4>Stack trace:</h4> 
    <pre><?php echo $this->exception->getTraceAsString() ?></pre> 

    <h4>Request Parameters:</h4> 
    <? var_dump($this->request->getParams()); ?>

<? endif; ?>

Your application should work now. Try browsing to / and to /foo. You should end up seeing your index/index and error/error actions.

Unit testing

Another point which took me a little longer to figure out was how to add unit testing with PHPUnit. I installed it via PEAR and got version 3.3.16.

Add config and helper files

A central config file for PHPUnit located at tests/phpunit.xml. The bootstrap attribute tells PHPUnit to execute that file before running any tests.

<phpunit bootstrap="./TestHelper.php" colors="true">
    <testsuite name="MyProject">
        <directory>./</directory>
    </testsuite>
</phpunit>

A test helper file which sets include paths located at tests/TestHelper.php:

<?php
define('BASE_PATH', realpath(dirname(__FILE__) . '/../'));
define('APPLICATION_PATH', BASE_PATH . '/application');

// Include path
set_include_path(
    '.'
    . PATH_SEPARATOR . BASE_PATH . '/library'
    . PATH_SEPARATOR . get_include_path()
);

// Define application environment
define('APPLICATION_ENV', 'testing');

require_once 'ControllerTestCase.php';

A base class for controller tests which sets up the needed environment located at tests/ControllerTestCase.php:

<?php
require_once 'Zend/Application.php';
require_once 'Zend/Test/PHPUnit/ControllerTestCase.php';

abstract class ControllerTestCase extends Zend_Test_PHPUnit_ControllerTestCase
{
    public $application;

    public function setUp()
    {
        $this->application = new Zend_Application(
            APPLICATION_ENV,
            APPLICATION_PATH . '/configs/application.ini'   
        );

        $this->bootstrap = array($this, 'appBootstrap');
        parent::setUp();
    }

    public function appBootstrap()
    {
        $this->application->bootstrap();
    }
}

Add unit tests

Let’s add a simple unit test for the index controller at tests/application/controllers/IndexControllerTest.php.

<?php
class IndexControllerTest extends ControllerTestCase
{
    public function testIndexAction() {
        $this->dispatch('/');
        $this->assertController('index');
        $this->assertAction('index');
    }

    public function testErrorURL() {
        $this->dispatch('foo');
        $this->assertController('error');
        $this->assertAction('error');
    }
}

Test!

Now you should be able to run the tests. Change to the tests directory and run phpunit.

cd tests
phpunit --configuration phpunit.xml --verbose

This should run 2 tests and complete successfully.

Be lazy

No, just kidding ;) But I am, when it comes to typing. So I wrote a little bash script to run the tests without having to type the whole phpunit command. I dropped it under bin/run_tests.

#!/bin/bash
TESTS_DIR=$(dirname $0)/../tests/

cd $TESTS_DIR
phpunit --configuration phpunit.xml --verbose
echo ""
echo ""

Don’t forget to make the script executable:

chmod +x bin/run_tests

Note: As Matthew stated, the script is not necessary if your config file is called phpunit.xml. So just chdir to the tests directory and run phpunit if you don’t have any parameters you’d like to set on the command line.

Be even more lazy!

Download a zip archive of the project or grab your copy at GitHub :)

Sources

  • http://weierophinney.net/matthew/ Matthew Weier O’Phinney

    Actually, phpunit will automatically load a configuration file in the current directory if it is named phpunit.xml — so all you need to run is ‘phpunit’ at the command line in order to run your test suite. This obviates the need for your run_tests script.

    • http://maff.ailoo.net/ Mathias

      @Matthew thanks I updated the article :)

  • http://weierophinney.net/matthew/ Matthew Weier O’Phinney

    Actually, phpunit will automatically load a configuration file in the current directory if it is named phpunit.xml — so all you need to run is ‘phpunit’ at the command line in order to run your test suite. This obviates the need for your run_tests script.

    • http://maff.ailoo.net/ Mathias

      @Matthew thanks I updated the article :)

  • Ryan

    Very nice post. Was extremely helpful.

  • Ryan

    Very nice post. Was extremely helpful.

  • phifeshaheed

    Thank you for this article, it really helps with getting started with 1.8 when all the books i have i still talkin 1.7 and earlier language

  • phifeshaheed

    Thank you for this article, it really helps with getting started with 1.8 when all the books i have i still talkin 1.7 and earlier language

  • Brad

    Many, many thanks Mathias. Most of the Zend Testing setup pages offer little to no detail. This is a great intro for people learning about Zend + PHPUnit.

  • Brad

    Many, many thanks Mathias. Most of the Zend Testing setup pages offer little to no detail. This is a great intro for people learning about Zend + PHPUnit.

  • http://tfountain.co.uk/ Tim Fountain

    I followed an almost identical approach to yours, however I kept getting this cryptic error:

    Zend_Loader::include(db.php): failed to open stream: No such file or directory

    this error would always occur whenever the second controller I was testing kicked in, regardless of what that controller was or what the test did. I assume therefore it happens when the second Zend_Application object is created.

    I solved it by storing the Zend_Application object in the registry, and checking Zend_Registry::isRegistered() in setUp(). Not ideal, but it’ll do for now – perhaps this will help someone else with the same trouble.

  • http://tfountain.co.uk/ Tim Fountain

    I followed an almost identical approach to yours, however I kept getting this cryptic error:

    Zend_Loader::include(db.php): failed to open stream: No such file or directory

    this error would always occur whenever the second controller I was testing kicked in, regardless of what that controller was or what the test did. I assume therefore it happens when the second Zend_Application object is created.

    I solved it by storing the Zend_Application object in the registry, and checking Zend_Registry::isRegistered() in setUp(). Not ideal, but it’ll do for now – perhaps this will help someone else with the same trouble.

  • http://maff.ailoo.net/ Mathias

    @Tim do you request a db.php anywhere? Zend_Loader got some refactoring in 1.8, may be that you get the error because of this.

  • http://maff.ailoo.net/ Mathias

    @Tim do you request a db.php anywhere? Zend_Loader got some refactoring in 1.8, may be that you get the error because of this.

  • http://tfountain.co.uk/ Tim Fountain

    Nope, nowhere in my application is there a db.php, nor am I calling a class called Db, db or DB; and I am using the new autoloader. I think it relates to the DB resource created by Zend_Application, as I have some resource.db.* lines in my application.ini. If Zend_Application is only created once (by storing it in the registry), the error disappears.

  • http://tfountain.co.uk/ Tim Fountain

    Nope, nowhere in my application is there a db.php, nor am I calling a class called Db, db or DB; and I am using the new autoloader. I think it relates to the DB resource created by Zend_Application, as I have some resource.db.* lines in my application.ini. If Zend_Application is only created once (by storing it in the registry), the error disappears.

  • http://davidmintz.org/ David Mintz

    Oh yeah!!!!!!!!!!

    Now if I can just pry my lips off your boots and express my gratitude with a little more dignity…. Seriously, though: thank you.

  • http://davidmintz.org/ David Mintz

    Oh yeah!!!!!!!!!!

    Now if I can just pry my lips off your boots and express my gratitude with a little more dignity…. Seriously, though: thank you.

  • Leandro

    How would it work if the application was divided into modules (default, admin, etc)?

    • http://davidmintz.org/ David Mintz

      @leandro

      Good news: it works the same as when there’s just a default module. First, set up your module — let’s say it’s called ‘admin.’ Then:

      “`php
      public function testAdminIndexAction() {
      $this->dispatch(‘/admin/’);
      $this->assertModule(‘admin’);
      $this->assertController(‘index’);
      $this->assertAction(‘index’);
      }
      “`

    • Ryan

      I would say it’s a great guide which helps me especially in Unit Testing!

      I’m wondering I tried to do with your admin module testing. It does not seem to work. Can you please help? Thanks

      My project structure is below;


      application/
      modules/
      users/
      admin/

  • Leandro

    How would it work if the application was divided into modules (default, admin, etc)?

    • http://davidmintz.org/ David Mintz

      @leandro

      Good news: it works the same as when there’s just a default module. First, set up your module — let’s say it’s called ‘admin.’ Then:

      “`php
      public function testAdminIndexAction() {
      $this->dispatch(‘/admin/’);
      $this->assertModule(‘admin’);
      $this->assertController(‘index’);
      $this->assertAction(‘index’);
      }
      “`

    • Ryan

      I would say it’s a great guide which helps me especially in Unit Testing!

      I’m wondering I tried to do with your admin module testing. It does not seem to work. Can you please help? Thanks

      My project structure is below;


      application/
      modules/
      users/
      admin/

  • http://typeoneerror.com Ben

    Great post. Really enjoyed reading it and it helped me get over a few annoying .ini problems I was having with 1.8.

  • http://typeoneerror.com Ben

    Great post. Really enjoyed reading it and it helped me get over a few annoying .ini problems I was having with 1.8.

  • Pingback: Unit Testing with the Zend Framework with Zend_Test and PHPUnit | free Zend Framework screencasts - Zendcasts()

  • Pingback: » Have you made the jump to Zend Framework 1.8?()

  • http://www.devhands.com Aleksandr Tsertkov

    Great post Mathias!

    There is one problem though. If you initialize View in a bootstrap resource method (Bootstrap::_initView()) you will lose your view resource settings defined in a config file (resources.view.encoding = “UTF-8″).

    Instead of instantiating new View instance manually via:

    “`php
    $view = new Zend_View();
    “`

    you could use:

    “`php
    $view = $this->bootstrap(‘view’)->getResource(‘view’);
    “`

    • http://www.devhands.com Aleksandr Tsertkov

      One more thing :) You will need to rename “View” to something else in an _initView() method to prevent names collision. Here is my View resource method:

      “`php
      protected function _initAView()
      {
      $view = $this->bootstrap(‘view’)->getResource(‘view’);
      $view->doctype(‘XHTML1_STRICT’);
      $view->headTitle($this->getResource(‘config’)->sitename)
      ->setSeparator(‘ – ‘);
      return $view;
      }
      “`

  • http://www.devhands.com Aleksandr Tsertkov

    Great post Mathias!

    There is one problem though. If you initialize View in a bootstrap resource method (Bootstrap::_initView()) you will lose your view resource settings defined in a config file (resources.view.encoding = “UTF-8″).

    Instead of instantiating new View instance manually via:

    “`php
    $view = new Zend_View();
    “`

    you could use:

    “`php
    $view = $this->bootstrap(‘view’)->getResource(‘view’);
    “`

    • http://www.devhands.com Aleksandr Tsertkov

      One more thing :) You will need to rename “View” to something else in an _initView() method to prevent names collision. Here is my View resource method:

      “`php
      protected function _initAView()
      {
      $view = $this->bootstrap(‘view’)->getResource(‘view’);
      $view->doctype(‘XHTML1_STRICT’);
      $view->headTitle($this->getResource(‘config’)->sitename)
      ->setSeparator(‘ – ‘);
      return $view;
      }
      “`

  • http://blog.psax.de Ben

    I get the same error as “Tim Fountain” described some comments above, if I try to add a second test (i.e. Index2ControllerTest or anything like that) i get the message that “db.php” can not be found.

    If i try the solution from Tim with registering Zend_Application in registry the error disappears but than I get the error that no default module is defined, if I do so in application.ini with resources.frontController.defaultModule = “default” nothing happens, the error still appears.

    Has anyone a working solution for this issue?

    I only find information about Unit Testing a normal structure, but nowhere is described how I can use Zend_Test for Unit Testing my application structure when I’m using modules!

    Thanks for the help in advance guys!

  • http://blog.psax.de Ben

    I get the same error as “Tim Fountain” described some comments above, if I try to add a second test (i.e. Index2ControllerTest or anything like that) i get the message that “db.php” can not be found.

    If i try the solution from Tim with registering Zend_Application in registry the error disappears but than I get the error that no default module is defined, if I do so in application.ini with resources.frontController.defaultModule = “default” nothing happens, the error still appears.

    Has anyone a working solution for this issue?

    I only find information about Unit Testing a normal structure, but nowhere is described how I can use Zend_Test for Unit Testing my application structure when I’m using modules!

    Thanks for the help in advance guys!

  • Federico

    I would suggest not using that rewrite rule. The behavior changes depending on the environment.

    For example, on mine:

    HTTP GET /
    echo $frontController->getRequest()->getRequestUri();
    /indexhtml

    And it should be:
    /index

    • http://maff.ailoo.net/ Mathias

      Hi Federico,

      sorry, seems that I completely missed your comment. As far as I remember I took the rewrite rule either from the ZF docs or it was created by Zend_Tool. What kind of rewrite rule do you use?

  • Federico

    I would suggest not using that rewrite rule. The behavior changes depending on the environment.

    For example, on mine:

    HTTP GET /
    echo $frontController->getRequest()->getRequestUri();
    /indexhtml

    And it should be:
    /index

    • http://maff.ailoo.net/ Mathias

      Hi Federico,

      sorry, seems that I completely missed your comment. As far as I remember I took the rewrite rule either from the ZF docs or it was created by Zend_Tool. What kind of rewrite rule do you use?

  • http://richardknop.com/ Richard Knop

    Great and useful article :)

    atm, I’m in a process of rewriting my ordinary spaghetti bootstrap file and instead writing something similar to this.

  • http://richardknop.com/ Richard Knop

    Great and useful article :)

    atm, I’m in a process of rewriting my ordinary spaghetti bootstrap file and instead writing something similar to this.

  • http://lboynton.com L

    Thanks for a useful article. I myself put the bootstrap code in TestHelper in tests/application/bootstrap.php as the zf script creates this file.

    How would you go about testing models and your own classes you’ve put in the library? I assume you would create a ModelTestCase class similar to ControllerTestCase for models.

    • http://maff.ailoo.net/ Mathias

      Indeed I got an additional ModelTestCase which extends PHPUnit_Framework_TestCase instead of Zend_Test_PHPUnit_ControllerTestCase. Maybe not the best solution as there is some redundand code, but for me it’s OK right now.

  • http://lboynton.com L

    Thanks for a useful article. I myself put the bootstrap code in TestHelper in tests/application/bootstrap.php as the zf script creates this file.

    How would you go about testing models and your own classes you’ve put in the library? I assume you would create a ModelTestCase class similar to ControllerTestCase for models.

    • http://maff.ailoo.net/ Mathias

      Indeed I got an additional ModelTestCase which extends PHPUnit_Framework_TestCase instead of Zend_Test_PHPUnit_ControllerTestCase. Maybe not the best solution as there is some redundand code, but for me it’s OK right now.

  • http://www.noginn.com Tom Graham

    Great post, I was trying to figure out how to use Zend_Application with functional tests. Seems obvious now! :)

    Thanks.

  • http://www.noginn.com Tom Graham

    Great post, I was trying to figure out how to use Zend_Application with functional tests. Seems obvious now! :)

    Thanks.

  • http://app.etizer.org Laurent

    Thanks a lot for your post. It really helped me setting up PHPUnit with Zend Framework.

  • http://app.etizer.org Laurent

    Thanks a lot for your post. It really helped me setting up PHPUnit with Zend Framework.

  • mient-jan

    Best post ever. This realy helps a lot.

  • mient-jan

    Best post ever. This realy helps a lot.

  • Angel

    Hi…great post! I was wondering if you can help me with something, I am having problems showing errors explicitly with your setup (even after setting phpSettings.display_startup_errors = 1 and phpSettings.display_errors = 1)

    before i could get strict error output by using the script block below (but it doen’nt work with your setup) :

    // ERROR REPORTING
    error_reporting(E_ALL|E_STRICT);
    ini_set(‘display_errors’,’on’);

    any help would be appreciated!

  • Angel

    Hi…great post! I was wondering if you can help me with something, I am having problems showing errors explicitly with your setup (even after setting phpSettings.display_startup_errors = 1 and phpSettings.display_errors = 1)

    before i could get strict error output by using the script block below (but it doen’nt work with your setup) :

    // ERROR REPORTING
    error_reporting(E_ALL|E_STRICT);
    ini_set(‘display_errors’,’on’);

    any help would be appreciated!

  • http://pro100pro.com Yaroslav Vorozhko

    Hi Maff, great tutorial.
    I am translated it to russian here http://pro100pro.com/nastraivaem-zend-application.

    Thanks, Zend Framework Fan.

    • http://maff.ailoo.net/ Mathias

      @Yaroslaw Thank you for the translation and the info :)

      — Mathias

  • http://pro100pro.com Yaroslav Vorozhko

    Hi Maff, great tutorial.
    I am translated it to russian here http://pro100pro.com/nastraivaem-zend-application.

    Thanks, Zend Framework Fan.

    • http://maff.ailoo.net/ Mathias

      @Yaroslaw Thank you for the translation and the info :)

      — Mathias

  • Pingback: PHP Podcasts » Unit Testing with the Zend Framework with Zend_Test and PHPUnit()

  • jazz

    hello ,I use WAMP and install in D:wwwwamp,then downloaded you code,but
    D:wwwwampwww>phpunit –configuration zf_1.8b1_apptestsphpunit.xml

    Fatal error: Uncaught exception ‘RuntimeException’ with message ‘File “” does no
    t exist.’ in D:wwwwampbinphpphp5.2.6PEARPHPUnitUtilFileloader.php:116
    Stack trace:
    #0 D:wwwwampbinphpphp5.2.6PEARPHPUnitTextUICommand.php(536): PHPUnit_Ut
    il_Fileloader::load(‘./TestHelper.ph…’)
    #1 D:wwwwampbinphpphp5.2.6PEARPHPUnitTextUICommand.php(74): PHPUnit_Tex
    tUI_Command::handleArguments()
    #2 D:wwwwampbinphpphp5.2.6phpunit(52): PHPUnit_TextUI_Command::main()
    #3 {main}
    thrown in D:wwwwampbinphpphp5.2.6PEARPHPUnitUtilFileloader.php on lin
    e 116

    I do not know the reason, and http://localhost/zf_1.8b1_app it can work.

  • jazz

    hello ,I use WAMP and install in D:\www\wamp,then downloaded you code,but
    D:\www\wamp\www>phpunit –configuration zf_1.8b1_app\tests\phpunit.xml

    Fatal error: Uncaught exception ‘RuntimeException’ with message ‘File “” does no
    t exist.’ in D:\www\wamp\bin\php\php5.2.6\PEAR\PHPUnit\Util\Fileloader.php:116
    Stack trace:
    #0 D:\www\wamp\bin\php\php5.2.6\PEAR\PHPUnit\TextUI\Command.php(536): PHPUnit_Ut
    il_Fileloader::load(‘./TestHelper.ph…’)
    #1 D:\www\wamp\bin\php\php5.2.6\PEAR\PHPUnit\TextUI\Command.php(74): PHPUnit_Tex
    tUI_Command::handleArguments()
    #2 D:\www\wamp\bin\php\php5.2.6\phpunit(52): PHPUnit_TextUI_Command::main()
    #3 {main}
    thrown in D:\www\wamp\bin\php\php5.2.6\PEAR\PHPUnit\Util\Fileloader.php on lin
    e 116

    I do not know the reason, and http://localhost/zf_1.8b1_app it can work.

  • http://davidmintz.org/ David Mintz

    @jazz

    I had the same problem until I took another look and saw that i had placed my bootstrap file in tests/application rather than tests.

    HTH

  • http://davidmintz.org/ David Mintz

    @jazz

    I had the same problem until I took another look and saw that i had placed my bootstrap file in tests/application rather than tests.

    HTH

  • yoursjzz

    Do you mean I shpould copy the bootstrap.php from /application to /tests?
    Need your help.

  • yoursjzz

    Do you mean I shpould copy the bootstrap.php from /application to /tests?
    Need your help.

  • Pingback: Zend Application: Guía para empezar()

  • http://davidmintz.org David Mintz

    Just sayin’, follow the instructions like the man says. Follow them slavishly, step by step, one step at a time, your mind in a state of the purest possible single-pointed concentration… And make sure PHPUnit can find the bootstrap file in the location you tell it in phpunit.xml

  • http://davidmintz.org David Mintz

    Just sayin’, follow the instructions like the man says. Follow them slavishly, step by step, one step at a time, your mind in a state of the purest possible single-pointed concentration… And make sure PHPUnit can find the bootstrap file in the location you tell it in phpunit.xml

  • Mortal from minsk

    I’m having a problem – when i type http://localhost i c welcome to framework, it’s ok. but when i type http://localhost/index/index/ or http://localhost/index/ i c ‘Not found – /index/index/ or /index/ is not found on the server. what’s the problem is? thanks.

    • http://maff.ailoo.net/ Mathias

      Most likely you do not have mod_rewrite enabled on your Server (look at the Apache config) or your .htaccess file in the public folder isn’t working right.

    • http://davidmintz.org/ David Mintz

      Remember that you not only have to enable mod_rewrite, but also make sure there’s a “AllowOverride All” directive in the block of your web server configuration, otherwise .htaccess will have no effect.

    • http://davidmintz.org/ David Mintz

      Remember also that you not only have to have mod_rewrite enabled, but also make sure there’s a “AllowOverride All” directive in the block of your web server configuration, otherwise .htaccess will have no effect.

    • http://maff.ailoo.net/ Mathias

      Thanks David, completely forgot about that possibility.

  • http://no_website.com Mortal from minsk

    I’m having a problem – when i type http://localhost i c welcome to framework, it’s ok. but when i type http://localhost/index/index/ or http://localhost/index/ i c ‘Not found – /index/index/ or /index/ is not found on the server. what’s the problem is? thanks.

    • http://maff.ailoo.net/ Mathias

      Most likely you do not have mod_rewrite enabled on your Server (look at the Apache config) or your .htaccess file in the public folder isn’t working right.

    • http://davidmintz.org/ David Mintz

      Remember that you not only have to enable mod_rewrite, but also make sure there’s a “AllowOverride All” directive in the block of your web server configuration, otherwise .htaccess will have no effect.

    • http://davidmintz.org/ David Mintz

      Remember also that you not only have to have mod_rewrite enabled, but also make sure there’s a “AllowOverride All” directive in the block of your web server configuration, otherwise .htaccess will have no effect.

    • http://maff.ailoo.net/ Mathias

      Thanks David, completely forgot about that possibility.

  • http://buddhamag.net buddhamagnet

    Hi all – I have followed the instructions above to the letter but when I run unit tests against my controllers all but the IndexController come back with a 500 and reroute to the ErrorController.

    Anyone else have this issue and can anyone help?

  • http://buddhamag.net buddhamagnet

    Hi all – I have followed the instructions above to the letter but when I run unit tests against my controllers all but the IndexController come back with a 500 and reroute to the ErrorController.

    Anyone else have this issue and can anyone help?

  • Jacques Marques

    How can I run this example in Zend Studio 7.0?

    Thanks

  • Jacques Marques

    How can I run this example in Zend Studio 7.0?

    Thanks

  • Pingback: Federico Cargnelutti (fedecarg) 's status on Sunday, 18-Oct-09 22:59:47 UTC - Identi.ca()

  • http://shortrecipes.blogspot.com/ W

    Thank you very much! This post helped me to start my own testing in ZF. However, if someone is using lampp 1.7.2, there is a problem, because PHPUnit in lampp is to old and it must be upgraded. I wrote short post about how to do this upgrade here . Hope it will be useful.

  • http://shortrecipes.blogspot.com/ W

    Thank you very much! This post helped me to start my own testing in ZF. However, if someone is using lampp 1.7.2, there is a problem, because PHPUnit in lampp is to old and it must be upgraded. I wrote short post about how to do this upgrade here . Hope it will be useful.

  • Krishan

    a very good article to help a beginner to set up a zend frame work application….Thanks a lot…..

  • Krishan

    a very good article to help a beginner to set up a zend frame work application….Thanks a lot…..

  • http://wheresrhys.co.uk Rhys

    This is a great tutorial thanks.

    But one question I have is that you put a lot more in application.ini than I’ve seen in other zend implementations. What are the reasons for putting stuff here rather than in bootstrap.php or index.php?

    Cheers

  • http://wheresrhys.co.uk Rhys

    This is a great tutorial thanks.

    But one question I have is that you put a lot more in application.ini than I’ve seen in other zend implementations. What are the reasons for putting stuff here rather than in bootstrap.php or index.php?

    Cheers

  • Greg

    Hi,
    I have a problem with running it in my application in Zend Studio 7.1

    I get:
    Fatal error: Class ‘ControllerTestCase’ not found in C:Program Files (x86)ZendApache2htdocsekorkitestsapplicationcontrollersIndexControllerTest.php on line 3

    Could you help me?

    • http://www.simplesites.ws Phil

      @Greg:
      Had the same problem, in my case the OS-package-installer got me an old phpunit. As a consequence the bootstrap file wasn’t executed. After update to the newest version, all worked fine.

  • Greg

    Hi,
    I have a problem with running it in my application in Zend Studio 7.1

    I get:
    Fatal error: Class ‘ControllerTestCase’ not found in C:\Program Files (x86)\Zend\Apache2\htdocs\ekorki\tests\application\controllers\IndexControllerTest.php on line 3

    Could you help me?

    • http://www.simplesites.ws Phil

      @Greg:
      Had the same problem, in my case the OS-package-installer got me an old phpunit. As a consequence the bootstrap file wasn’t executed. After update to the newest version, all worked fine.

  • PixelMaker

    Hi,

    If I want to use $this->module in my index.phtml, what Should I need to place in Bootstrap.php file.

    I will explain:

    If you use this print_r($this->_getAllParams()); in any of your controllers, suppose contactController;

    it will display
    Array (
    [controller] => contact
    [action] => index
    [module] => default
    )

    instead of using that function (getAllParams()), I just want to initialize the controller, module, action values in bootstrap itself, so that I can use the values anywhere (controller / view) like $this->view->module in controller and $this->module in my views.

    Please let me know how can we achieve this.

    Thanks in Advance.
    PixelMaker.

  • PixelMaker

    Hi,

    If I want to use $this->module in my index.phtml, what Should I need to place in Bootstrap.php file.

    I will explain:

    If you use this print_r($this->_getAllParams()); in any of your controllers, suppose contactController;

    it will display
    Array (
    [controller] => contact
    [action] => index
    [module] => default
    )

    instead of using that function (getAllParams()), I just want to initialize the controller, module, action values in bootstrap itself, so that I can use the values anywhere (controller / view) like $this->view->module in controller and $this->module in my views.

    Please let me know how can we achieve this.

    Thanks in Advance.
    PixelMaker.

  • Pingback: blog.nielslange.de » Test Driven Development (TTD) with the Zend Framework()

  • http://www.taklia.com Bitsurs

    This article really explains exactly what you have to know to build websites in a minutes, using Zend Framework!
    many thanks

  • http://www.taklia.com Bitsurs

    This article really explains exactly what you have to know to build websites in a minutes, using Zend Framework!
    many thanks

  • http://www.biblepraise.org Steve

    Matthias,

    Thank you so much for this article. I practically grew some grey hair trying to understand Unit Testing of ZF projects. Some tutorials were so difficult to understand and their examples didn’t work. With yours, I got it right the first time!

    Thank you very much!

  • http://www.biblepraise.org Steve

    Matthias,

    Thank you so much for this article. I practically grew some grey hair trying to understand Unit Testing of ZF projects. Some tutorials were so difficult to understand and their examples didn’t work. With yours, I got it right the first time!

    Thank you very much!

  • Chethan1ce007

    Thats a great post really helped a lot
    when i start to implement the same with my module
    am getting this error
    PHP Fatal error: Call to a member function getOptions() on a non-object in /var/www/ourbankBrazil/library/Mod/Controller/Action/Helper/LayoutLoader.php on line 9

    Fatal error: Call to a member function getOptions() on a non-object in /var/www/ourbankBrazil/library/Mod/Controller/Action/Helper/LayoutLoader.php on line 9

  • http://twitter.com/bartmcleod Bart McLeod

    Hi Matthias,

    Your unit test example is easily found by Google, but it is not completely correct. It in fact triggers issue http://zendframework.com/issues/browse/ZF-8193

    In particular, the setup implementation should be different:

    public function setUp()
    {
    $this->bootstrap = new Zend_Application(
    APPLICATION_ENV,
    APPLICATION_PATH . ‘/configs/application.ini’
    );

    parent::setUp();
    }

    The issue is not an issue, just wrong usage. I stumbled upon it when I used your code as an example for a controller unit test.

    Regards,Bart McLeod