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.

Zend Framework: Passing objects to Partial Views

Hector Virgen gave some hints about how to pass object into partial views and partial loops;

You can pass objects to partials, just pass them in an array:

<?= $this->partial('mypartial.phtml', array('topic' => $topic')) ?>

The partial helper will take the keys of that array and create view vars out of them, so you can access it like this from within the partial:

<?= $this->topic->getDescription() ?>

If you want to use objects with a partial loop, you can call setObjectKey() on the partialLoop helper and pass in an array of objects:

<?= $this-partialLoop()->setObjectKey('topic')
->partialLoop('mypartial.phtml', $topics) ?>

Editors remark: Easy once you seen it done 🙂

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

Doctrine – Doctrine 2: Give me my constructor back

John Wage writes; At ConFoo 2010 during my presentation, someone asked about the constructor of entities in Doctrine 2 and whether or not it could be used. I think this is something worth writing about since in Doctrine 1 this was not possible. The constructor was hi-jacked from you and used internally by Doctrine.

In Doctrine 2 it is possible to define the constructor in your entity classes and is not required to be a zero argument constructor! That&apos;s right, Doctrine 2 never instantiates the constructor of your entities so you have complete control!

This is possible due to a small trick which is used by two other projects, php-object-freezer and Flow3. The gist of it is we store a prototype class instance that is unserialized from a hand crafted serialized string where the class name is concatenated into the string. The result when we unserialize the string is an instance of the class which is stored as a prototype and cloned everytime we need a new instance during hydration.

Have a look at the method responsible for this:

Read the full article at; Doctrine – Doctrine 2: Give me my constructor back.

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.