Integrating Zend_Tool Into Your Application

Jon Lebensold shows you how to use the Zend Tool in useful ways; This screencast should help you setup Zend_Tool in your Zend Framework application. Zend_Tool is a command line entry point into your application. Currently, Zend_Tool is used to scaffold (build generic files) the Zend Framework project structure, modules, controllers, database table classes and other tedious processes. The goal of this video is to start looking at how we can generate our own Manifest and Provider classes so that custom command line tools can be integrated into the Zend Framework application.

The advantage of such integration is far reaching: deployable web applications using the Zend Framework can have “installers” and other frameworks, like Doctrine, can easily become first class citizens within the Zend Framework eco-system.

Grab a copy of the project or browse the repository.

via Zendcasts.

Zend Framework: Module Specific Layout Plugin

Graham Anderson posted an useful workaround for the module specific layout problem;
The default layout plugin will accept a stack of paths in LIFO order.
This allows a very simple hack to always ensure that any module can have it’s own default layout which will automatically override the default module layout.


class App_Controller_Plugin_Layout extends Zend_Controller_Plugin_Layout {

public function __construct ($layout = null)
{
parent::__construct ($layout);
}

public function preDispatch(Zend_Controller_Request_Abstract $request)
{
// Insert current module layout dir to to overide any default layouts
if ( $request->getModuleName() != 'default' ) {

$layoutPath = APPLICATION_PATH . '/modules/' .
$request->getModuleName() . '/views/layouts';

$paths = array();
$paths[] = $this->getLayout()->getViewScriptPath();
$paths[] = $layoutPath;

$this->getLayout()->setViewScriptPath($paths);
}
}
}

Asssuming you set the following application config value:


resources.layout.layout = "default"

Now any module with a default.phtml layout will override the default module layout.

e.g APPLICATION_PATH/modules/foobar/views/layouts/default.phtml

Cheers the noo,
Graham

Better Zend Framework Documentation

Chris Morrell comes with a very nice intermediate solution to ZF documentation hassles, he writes;

If you’ve every tried to navigate the Zend Framework documentation’s longer pages you’ve probably looked everywhere for a table of contents. Sure, there’s a TOC for the major sections of the component, but if you’re looking for a specific part of a page (or an overview of what that page covers) you’re out of luck. For example, take a look at the Zend_Validate list of standard validation classes. Now try to find the documentation on the URI validator. Can’t find it? That’s ’cause it doesn’t exist. Too bad you had to scroll down through 39 page-lengths’ worth of documentation to find that out.

Wouldn’t it be nice if you’d had something like this:…

Read on “Better Zend Framework Documentation” by Chris Morrell.

PHP 5.3 namespaces for the rest of us

According to the official documentation, PHP namespaces have been designed to prevent name collisions between classes from different packages and to avoid the use of very long names in the code to refer to classes or functions—nobody really wants to have to deal with something called Zend_Db_Adapter_Mysqli or PHPUnit_Framework_Constraint_IsInstanceOf, after all. This means that namespaces help a developer write code that is both more concise and clearer—a direction which is always an improvement towards expressiveness.

Within the PHP implementation of namespaces, these names will be ideally refactored to Zend\Db\Adapter\Mysqli and PHPUnit\Framework\Constraint\IsInstanceOf, where \ is the namespace separator. In the codebase, however, there will typically be very few references to these classes with their fully qualified name, because it is possible to import entire namespaces in a script and then use the class names directly, making the code easier to follow and unambiguous to write.

In fact, the definition of a namespace class itself does not contain its fully qualified name. For example, this would be the source file of an hypothetical MyLibrary\TypeOfComponents\MyClass class:

<?PHP
namespace MyLibrary\TypeOfComponents;
class MyClass
{
// ...
}

The convention when writing namespace-enabled code is that of creating a folder structure that reflects the individual components of a namespace (for example, MyClass would be in the MyLibrary/TypeOfComponents directory. This helps standardizing the autoloading process.

Read the full story PHP 5.3 namespaces for the rest of us | php|architect.

Introducing a Tool for Namespacing PHP5 Prefixed codebases

Ralph Schindler writes;
Hey All-

Over the past few days, I’ve been working on a tool that I think might help expedite the task of converting all of our code into a Namespaced codebase.  Currently, it’s been tested on simple components like Zend_Acl and Zend_Filter and over the course of the next few days, we’ll be applying it to some of the more complex components.

What it does..

This tool is a command line tool.  First, you may get it from my GitHub repository:

http://github.com/ralphschindler/PHPTools

git clone http://github.com/ralphschindler/PHPTools.git

-OR-

Just download the tar/gz/zip via the github interface.

Inside here you’ll find a bin/ library/ and test/ directory, the namespacer tool is located in this library.  To get the basic help screen, simply run ‘php bin/php-namespacer.php -h’.  This will give you a couple of available options to understand what the various command line switches do.  Personally, I create a link from somewhere in my path, usually $HOME/bin/php-namespacer to path/to/PHPTools/bin/php-namespacer.php, this makes it easier to run the command from anywhere in your filesystem.

To be able to get up and running with it quickly, I suggest running to tool in the following manner to get an idea of what it will produce:

bash> php-namespacer -l=../library/ -d=Zend/Acl -p=Zend -o=./tmp/ -m=./tmp/

Here are is what the above is going to do:

  • with the -l switch, you are telling it the location of a library this is typically the same directory you’d add to an include_path
  • with the -d switch, you are telling the tool that of all the classes it comes across in the library, only work on this particular directory
  • -p is the prefix we want to work on, in our case Zend/
  • -o is the directory where you want your new files written to
  • -m is the directory where an XML file will be produced of all the name translations that have taken place.

The full library is supplied so that the tool can iterate all files for class names that might be present inside the working directory’s files.

This is so that it knows what those translations will be once those components are eventually converted (assuming they are part of the same effort).

This tool will OPTIONALLY convert names in docblock ONLY if you have the pecl ext/docblock extension compiled and enabled (http://pecl.php.net/package/docblock).  Otherwise it will not touch the docblocks.

I have to admit that even though we are seeing some great results so far, this tool is still in it’s infancy.  We are opening it up to you for feedback and if you find it useful, to run it over your own code to see if it does the job of converting prefixed PHP5 code into namespaced PHP 5.3 code.

I’ll let everyone get a chance to run the tool and produce some output first before we start discussing the actual output and file contents.

For discussion purposes, we’ve been heavily looking at simpler components like Zend_Acl, Zend_Filter and Zend_Config- but don’t let that stop you from running it over other components or even your own code.

Let me know what you think!

Ralph Schindler

Namespacing ACL resources and Galahad_Acl

Chris Morrell writes; In most of my applications I like to handle authorization (querying the ACL) in one (or more) of three ways:

  • Authorize access to a model’s method
  • Authorize access to a controller action
  • Authorize access to an arbitrary “permission”

In general I find it’s best to keep authorization within the domain (querying the ACL within my models when they’re accessed) as this provides the most consistent behavior. For example, if I eventually add a REST API to my application I don’t have to duplicate all my authorization logic in the new REST controllers. When the application calls something like Default_Model_Post::save() it either saves or throws an ACL exception, no matter where it was called from. This is great in that it saves me from having to duplicate code and keeps my system more secure.

On the other hand, there are times when it’s just a lot easier to handle authorization in the controller. For example, if guests should never access my “Admin” module, it doesn’t make sense to ever let them access /admin/ URLs. Also, if you’re using Zend_Navigation, having ACL resources that match controller actions lets you utilize its ACL integration.

If you’re ever going to mix these two techniques, you’ll eventually bump into the case where a model and a controller share the same name. What if you need to set permissions on a “user” controller and different permissions on a “user” model? This is where namespacing comes into play. As suggested by the Zend Framework manual, I always name my controller action resources in the format mvc:module.controller.action. I name my model resources similarly, in the format model:module.modelName.methodName. In both theses cases, “mvc” and “model” are the namespace, and everything following the colon is the actual resource name. Now I can refer to my “admin” module as mvc:admin and the models within my admin module as model:admin.

This is where things get interesting.

Read on; “Namespacing ACL resources & Galahad_Acl”.

Chris continues; Right now I treat my models as resources with a special exception for the user model which is both a resource and a role. Then I actually make the models responsible for managing their own ACL permissions, both setting them up and querying them. To facilitate that, I have a base model class that does a few things. First it has a way to inject an ACL instance into the model as well as a way to pass an ACL instance as the default ACL for all models (which I do in my bootstrap). Second it automatically adds itself to that ACL (with the resource id model:moduleName.modelName). Finally, I have an _initAcl() method which is called when my model is instantiated which adds the appropriate rules to the ACL if they don’t already exist. Whenever my model is doing something that is access-controlled I check the ACL right then.

Here’s a simple code example:


class Default_Model_Post extends Galahad_Model_Entity
{
protected function _initAcl($acl)
{
// Deny permissions to anything on this model unless explicitly allowed
$acl->deny(null, $this);

// Allow guests to fetch the content of posts
$acl->allow('guest', $this, 'fetch');

// Allow admins to save changes to posts
$acl->allow('admin', $this, 'save');
}

public function save()
{
if (!$this->getAcl()->isAllowed($this->getRole(), $this, 'save')) {
throw new Galahad_Acl_Exception('Current user is not allowed to save posts.');
}

$dataMapper = $this->getDataMapper();
return $dataMapper->save($this);
}
}

There’s a little bit more happening in there (for example, I also have helper methods like getRole(), which either gets the role ID stored in the model or grabs it from Zend_Auth if available), but you should get the picture.

That way my access control is happening when the access itself is happening. No matter how my model is used, the ACL is always queried right when it matters. I also like setting up the ACL this way because all rules are loaded into the the ACL only when they could potentially apply (you never need the rules for a Post model if the current request never even loads the Post class).

This is something I’ve been thinking about a lot lately, and I’m just settling into this method. I just blogged about it a little over a week ago: “Namespacing ACL resources & Galahad_Acl” — if anyone has any comments I’d love to hear them

Zend Studio code formatter for Zend Framework

Updated: 2013-12-13 – Fixed links!

This is an excellent addition to you tools arsenal if you use Zend Studio and Zend Framework. Kudos to Ivo Jansh for publishing this!

Zend Studio is a great IDE and we use it a lot at Inviqa (in addition to NetBeans, PDT and Vim). One of the nice features is the code formatter that helps develop code according to agreed standards, which is useful to keep projects consistent.

One problem we have with the current versions of Zend Studio is that its default Zend Framework formatter is not consistent with the official Zend Framework coding standard. Luckily, that can be easily fixed. Sandy Pleyte, one of our developers, created a formatting file for Zend Studio that does adhere to the formal standard. There might be a few issues here and there but we’ve found it to work much better than the default one in Zend Studio. Because it might be helpful to others, we’re sharing the formatter file with anyone that’s interested. Download the file and read on for instructions.

 

Instructions

Download the above file to your desktop. Open the Zend Studio formatter preferences, which will give you the following screen:

Click the ‘import’ button and import the file that you’ve downloaded. Voila, your formatter now uses the Zend Framework official coding standards. If you find any issues with this formatter, please let us know in the comments below.

ATK formatter

If you use the ATK business framework, you might also be interested in the following formatter, which is similar to the ZF formatter but adds support for some of ATK’s coding conventions:

Have fun!

via techPortal.

A Simple Resource Injector for ZF Action Controllers

Matthew Weier O’Phinney writes a very useful article about resource injection; Brandon Savage approached me with an interesting issue regarding ZF bootstrap resources, and accessing them in your action controllers. Basically, he’d like to see any resource initialized by the bootstrap immediately available as simply a public member of his action controller.

So, for instance, if you were using the “DB” resource in your application, your controller could access it via $this->db.

I quickly drafted up a proof of concept for him using an action helper:


class My_ResourceInjector extends Zend_Controller_Action_Helper_Abstract
{
protected $_resources;

public function __construct(array $resources = array())
{
$this->_resources = $resources;
}

public function preDispatch()
{
$bootstrap = $this->getBootstrap();
$controller = $this->getActionController();
foreach ($this->_resources as $name) {
if ($bootstrap->hasResource($name)) {
$controller->$name = $bootstrap->getResource($name);
}
}
}

public function getBootstrap()
{
return $this->getFrontController()->getParam('bootstrap');
}
}

In this action helper, you would specify the specific resources you want injected via the $_resources property – which would be values you pass in. Each resource name would then be checked against those available in the bootstrap, and, if found, injected into the action controller as a property of the same name.

You would initialize it in your bootstrap:


class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
protected function _initResourceInjector()
{
Zend_Controller_Action_HelperBroker::addHelper(
new My_ResourceInjector(array(
'db',
'layout',
'navigation',
));
);
}
}

The above would map three resources: “db”, “layout”, and “navigation”. This means you can refer to them directly as properties in your controllers:


class FooController extends Zend_Controller_Action
{
public function barAction()
{
$this->layout->disableLayout();
$model = $this->getModel();
$model->setDbAdapter($this->db);
$this->view->assign(
'model' => $this->model,
'navigation' => $this->navigation,
);
}

// ...
}

This approach leads to some nice brevity — you no longer need to fetch the bootstrap from the instantiation arguments, and then fetch the resource.

I thought about it some more, and realized that there’s a few problems: How do you know what is being injected from within the controller? How do you control what is being injected.

So, I revised it to pull the expected dependencies from the action controller itself…

Read the complete article here A Simple Resource Injector for ZF Action Controllers.

Updated Zend_Dojo_View_Helper_Dialog

Charles Kyle Spraggs writes; I’ve been tinkering around with view helpers quite a bit now and I realized that a lot of what I did in the Dialog could be done much easier by extending the DijitContainer view helper. So, I rewrote the dialog view helper to extend DijitContainer and moved Zend_Dojo_View_Helper_Dijit_Extended to Zend_Dojo_View_Helper_Dojo_Extended because the methods are meant to be used statically similar to Zend_Dojo_View_Helper::setUseDeclarative(). For those of you that have no idea what I’m talking about you should read Zend_Dojo_View_Helper_Dialog first.

New code!

Zend_Dojo_View_Helper_Dojo_Extended

This little puppy exists for the sole purpose of adding stylesheets based on the set dojo path (local/CDN) and version (if CDN).

Usage

// Code from Zend_Dojo_View_Helper_Dialog which adds the stylesheet for enhanced dialogs
Zend_Dojo_View_Helper_Dojo_Extended::addStylesheet('/dojox/widget/Dialog/Dialog.css');

more at SpiffyJr’s Blogaroo.

Zend Framework MVC Request Lifecycle

Kevin Schroeder writes an excellent article about the MVC lifecycle thats a must read for anyone even thinking about writing ZF plugins; Matthew wrote up an article on modules in Zend_Application and that got me thinking a little bit. When I have done training for Zend Framework, one of the things that mystifies students to some extent is the whole plugin architecture and where things can go. There has been several articles written about it, but they tend to use code to describe it. I was only able to find a small handfull of articles that used some kind of chart to describe what goes on. Not that that’s a problem, but I had found that when I drew out the request lifecycle that it helped the students understand it better.

The chart on the right is a color-coded chart that shows when something is executed and where it is executed from. This chart is intentionally missing a whole bunch of things for the purpose of simplicity. If you want a more full explanation of the request lifecycle…

Read full story Friday Framework Highlight: Zend Framework MVC Request Lifecycle