public
Last active

ZF 1.x and Pimple Example

  • Download Gist
README.txt
1
An example of how to use Pimple DI with ZF 1.x
application/Bootstrap.php
PHP
1 2 3 4 5 6 7
<?php
 
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
 
 
}
application/configs/application.ini
INI
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
[production]
phpSettings.display_startup_errors = 0
phpSettings.display_errors = 0
includePaths.library = APPLICATION_PATH "/../library"
bootstrap.path = APPLICATION_PATH "/Bootstrap.php"
bootstrap.class = "Bootstrap"
appnamespace = "Application"
resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers"
resources.frontController.params.displayExceptions = 0
 
autoloadernamespaces.pimple = "Pimple"
autoloadernamespaces.ditest = "DITest"
 
[staging : production]
 
[testing : production]
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
resources.frontController.params.displayExceptions = 1
 
[development : production]
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
resources.frontController.params.displayExceptions = 1
application/controllers/ErrorController.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
<?php
 
class ErrorController extends Zend_Controller_Action
{
 
public function errorAction()
{
$errors = $this->_getParam('error_handler');
if (!$errors || !$errors instanceof ArrayObject) {
$this->view->message = 'You have reached the error page';
return;
}
switch ($errors->type) {
case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE:
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);
$priority = Zend_Log::NOTICE;
$this->view->message = 'Page not found';
break;
default:
// application error
$this->getResponse()->setHttpResponseCode(500);
$priority = Zend_Log::CRIT;
$this->view->message = 'Application error';
break;
}
// Log exception, if logger available
if ($log = $this->getLog()) {
$log->log($this->view->message, $priority, $errors->exception);
$log->log('Request Parameters', $priority, $errors->request->getParams());
}
// conditionally display exceptions
if ($this->getInvokeArg('displayExceptions') == true) {
$this->view->exception = $errors->exception;
}
$this->view->request = $errors->request;
}
 
public function getLog()
{
$bootstrap = $this->getInvokeArg('bootstrap');
if (!$bootstrap->hasResource('Log')) {
return false;
}
$log = $bootstrap->getResource('Log');
return $log;
}
 
 
}
application/controllers/IndexController.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14
<?php
 
class IndexController extends Zend_Controller_Action
{
public function init()
{
$this->c = $this->getInvokeArg('bootstrap')->getContainer();
}
 
public function indexAction()
{
$this->c['foo']->bar();
}
}
application/views/scripts/error/error.phtml
HTML+PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Zend Framework Default Application</title>
</head>
<body>
<h1>An error occurred</h1>
<h2><?php echo $this->message ?></h2>
 
<?php if (isset($this->exception)): ?>
<h3>Exception information:</h3>
<p>
<b>Message:</b> <?php echo $this->exception->getMessage() ?>
</p>
 
<h3>Stack trace:</h3>
<pre><?php echo $this->exception->getTraceAsString() ?>
</pre>
 
<h3>Request Parameters:</h3>
<pre><?php echo $this->escape(var_export($this->request->getParams(), true)) ?>
</pre>
 
<?php endif ?>
 
</body>
</html>
application/views/scripts/index/index.phtml
HTML+PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
<style>
a:link,
a:visited
{
color: #0398CA;
}
 
span#zf-name
{
color: #91BE3F;
}
 
div#welcome
{
color: #FFFFFF;
background-image: url(http://framework.zend.com/images/bkg_header.jpg);
width: 600px;
height: 400px;
border: 2px solid #444444;
overflow: hidden;
text-align: center;
}
 
div#more-information
{
background-image: url(http://framework.zend.com/images/bkg_body-bottom.gif);
height: 100%;
}
</style>
<div id="welcome">
<h1>Welcome to the <span id="zf-name">Zend Framework!</span></h1>
 
<h3>This is your project's main page</h3>
 
<div id="more-information">
<p><img src="http://framework.zend.com/images/PoweredBy_ZF_4LightBG.png" /></p>
<p>
Helpful Links: <br />
<a href="http://framework.zend.com/">Zend Framework Website</a> |
<a href="http://framework.zend.com/manual/en/">Zend Framework Manual</a>
</p>
</div>
</div>
docs/README.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
README
======
 
This directory should be used to place project specfic documentation including
but not limited to project notes, generated API/phpdoc documentation, or
manual files generated or hand written. Ideally, this directory would remain
in your development environment only and should not be deployed with your
application to it's final production location.
 
 
Setting Up Your VHOST
=====================
 
The following is a sample VHOST you might want to consider for your project.
 
<VirtualHost *:80>
DocumentRoot "/home/pascalopitz/Development/di_test/public"
ServerName di_test.local
 
# This should be omitted in the production environment
SetEnv APPLICATION_ENV development
 
<Directory "/home/pascalopitz/Development/di_test/public">
Options Indexes MultiViews FollowSymLinks
AllowOverride All
Order allow,deny
Allow from all
</Directory>
 
</VirtualHost>
library/DITest/Container.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
<?php
 
namespace DITest;
use Pimple;
 
class Container extends Pimple
{
public function __construct()
{
$this['foo'] = $this->share(function($this) {
$c = new \stdClass;
$c->bar = function() {
echo 'bar';
};
 
return $c;
});
}
}
library/Pimple.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
<?php
 
/*
* This file is part of Pimple.
*
* Copyright (c) 2009 Fabien Potencier
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is furnished
* to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
 
/**
* Pimple main class.
*
* @package pimple
* @author Fabien Potencier
*/
class Pimple implements ArrayAccess
{
private $values;
 
/**
* Instantiate the container.
*
* Objects and parameters can be passed as argument to the constructor.
*
* @param array $values The parameters or objects.
*/
function __construct (array $values = array())
{
$this->values = $values;
}
 
/**
* Sets a parameter or an object.
*
* Objects must be defined as Closures.
*
* Allowing any PHP callable leads to difficult to debug problems
* as function names (strings) are callable (creating a function with
* the same a name as an existing parameter would break your container).
*
* @param string $id The unique identifier for the parameter or object
* @param mixed $value The value of the parameter or a closure to defined an object
*/
function offsetSet($id, $value)
{
$this->values[$id] = $value;
}
 
/**
* Gets a parameter or an object.
*
* @param string $id The unique identifier for the parameter or object
*
* @return mixed The value of the parameter or an object
*
* @throws InvalidArgumentException if the identifier is not defined
*/
function offsetGet($id)
{
if (!array_key_exists($id, $this->values)) {
throw new InvalidArgumentException(sprintf('Identifier "%s" is not defined.', $id));
}
 
return $this->values[$id] instanceof Closure ? $this->values[$id]($this) : $this->values[$id];
}
 
/**
* Checks if a parameter or an object is set.
*
* @param string $id The unique identifier for the parameter or object
*
* @return Boolean
*/
function offsetExists($id)
{
return isset($this->values[$id]);
}
 
/**
* Unsets a parameter or an object.
*
* @param string $id The unique identifier for the parameter or object
*/
function offsetUnset($id)
{
unset($this->values[$id]);
}
 
/**
* Returns a closure that stores the result of the given closure for
* uniqueness in the scope of this instance of Pimple.
*
* @param Closure $callable A closure to wrap for uniqueness
*
* @return Closure The wrapped closure
*/
function share(Closure $callable)
{
return function ($c) use ($callable) {
static $object;
 
if (is_null($object)) {
$object = $callable($c);
}
 
return $object;
};
}
 
/**
* Protects a callable from being interpreted as a service.
*
* This is useful when you want to store a callable as a parameter.
*
* @param Closure $callable A closure to protect from being evaluated
*
* @return Closure The protected closure
*/
function protect(Closure $callable)
{
return function ($c) use ($callable) {
return $callable;
};
}
 
/**
* Gets a parameter or the closure defining an object.
*
* @param string $id The unique identifier for the parameter or object
*
* @return mixed The value of the parameter or the closure defining an object
*
* @throws InvalidArgumentException if the identifier is not defined
*/
function raw($id)
{
if (!array_key_exists($id, $this->values)) {
throw new InvalidArgumentException(sprintf('Identifier "%s" is not defined.', $id));
}
 
return $this->values[$id];
}
}
public/.htaccess
ApacheConf
1 2 3 4 5 6 7
 
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
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
<?php
 
// Define path to application directory
defined('APPLICATION_PATH')
|| define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));
 
// Define application environment
defined('APPLICATION_ENV')
|| define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'production'));
 
// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
realpath(APPLICATION_PATH . '/../library'),
get_include_path(),
)));
 
/** Zend_Application */
require_once 'Zend/Application.php';
 
// Create application, bootstrap, and run
$application = new Zend_Application(
APPLICATION_ENV,
APPLICATION_PATH . '/configs/application.ini'
);
 
 
$c = new DITest\Container();
$application->getBootstrap()->setContainer($c);
 
$application->bootstrap();
$application->run();
tests/application/controllers/IndexControllerTest.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
<?php
 
class IndexControllerTest extends Zend_Test_PHPUnit_ControllerTestCase
{
 
public function setUp()
{
$this->bootstrap = new Zend_Application(APPLICATION_ENV, APPLICATION_PATH . '/configs/application.ini');
 
$this->c = new DITest\Container();
$this->bootstrap->getBootstrap()->setContainer($this->c);
parent::setUp();
}
 
public function testIndexAction()
{
 
$mock = $this->getMock('bazClass', array('bar'), array(), '', FALSE);
$mock->expects($this->once())->method('bar');
 
$this->c['foo'] = function() use($mock) {
return $mock;
};
 
$params = array('action' => 'index', 'controller' => 'Index', 'module' => 'default');
$urlParams = $this->urlizeOptions($params);
$url = $this->url($urlParams);
$this->dispatch($url);
// assertions
$this->assertModule($urlParams['module']);
$this->assertController($urlParams['controller']);
$this->assertAction($urlParams['action']);
$this->assertQueryContentContains("div#welcome h3", "This is your project's main page");
}
 
 
}
tests/bootstrap.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
<?php
 
// Define path to application directory
defined('APPLICATION_PATH')
|| define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));
 
// Define application environment
defined('APPLICATION_ENV')
|| define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'testing'));
 
// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
realpath(APPLICATION_PATH . '/../library'),
get_include_path(),
)));
 
require_once 'Zend/Loader/Autoloader.php';
Zend_Loader_Autoloader::getInstance();
tests/phpunit.xml
XML
1 2 3 4 5 6 7 8 9 10 11 12 13 14
<phpunit bootstrap="./bootstrap.php">
<testsuite name="Application Test Suite">
<directory>./application</directory>
</testsuite>
<testsuite name="Library Test Suite">
<directory>./library</directory>
</testsuite>
<filter>
<whitelist>
<directory suffix=".php">../../library/Zend</directory>
</whitelist>
</filter>
</phpunit>

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.