Archive for the ‘Projects’ Category

More Doctrine 2 and Zend Framework integration goodies!

Friday, July 15th, 2011

Introduction

So, it’s been a while since I’ve posted but I’ve been hard at work the last few evenings on a few very cool features.

  1. I’ve written a Spiffy\Entity class that you can extend Doctrine 2 entities from to gain a few new features.
    • Zend Validator and Zend Filter annotations for entities.
    • You can now validate directly on the model (this is how it should be, IMO).
  2. I’ve written Spiffy\Form and Spiffy\Dojo\Form that integrates with Spiffy\Entity to do field type detection automatically somewhat similar to Symfony 2.
    • The form is smart enough to read the validators/filters from Spiffy\Entity. No more adding them directly to each form element!
    • You have the option to autoPersist Spiffy\Entity if the form validates.
  3. I’ve added three new form elements – Spiffy_Form_Element_Entity, Spiffy_Dojo_Form_Element_ComboBoxEntity, and Spiffy_Dojo_Form_Element_FilteringSelectEntity.
    • These elements allow you to map ManyToOne relations directly into your form. They’re still a work in progress (need to add store data option to the Dojo elements).
This project is currently in early development and I would not recommend use in a production environment! Follow the GitHub repository README for when I consider it stable.

Usage

Let’s get to the nitty gritty and build a complete registration form, controller, and entity. At the time of writing (7/15/2011) this post is accurate, however, the latest documentation is always available on my GitHub repository.

Setting up the Spiffy library

  1.  by downloading or cloning it into your include_path.
  2. Add the namespace to application.ini: autoloaderNamespaces[] = Spiffy
  3. Add the Spiffy pluginPaths to application.ini: pluginPaths.Spiffy_Application_Resource = “Spiffy/Application/Resource”
  4. Add the Spiffy annotations to Doctrine in your bootstrap: \Doctrine\Common\Annotations\AnnotationRegistr::registerFile(“Spiffy/Doctrine/Annotations/Zend/Validator.php”);
  5. Set the default entity manager for Spiffy\Form. \Spiffy\Form::setDefaultEntityManager($em);

Creating an entity

// My/Entity/User.php
namespace My\Entity;
use Spiffy\Entity;

/**
 * @ORM\Table(name="user")
 * @ORM\Entity
 */
class User extends Entity
{
        /**
         * @var integer $id
         *
         * @ORM\Column(name="id", type="integer")
         * @ORM\Id
         * @ORM\GeneratedValue(strategy="AUTO")
         */
        private $id;

        /**
         * @var string $username
         *
         * @ORM\Column(type="string")
         */
        private $username;

        /**
         * @var string $email
         *
         * @Assert\EmailAddress()
         * @ORM\Column(type="string")
         */
        private $email;

        /**
         * @var string $password
         *
         * @ORM\Column(type="string")
         */
        private $password;

        public function __toString() {
                return "{$this->username}";
        }

        public function getId() {
                return $this->id;
        }

        public function setId($id) {
                $this->id = $id;
        }

        public function getUsername() {
                return $this->username;
        }

        public function setUsername($username) {
                $this->username = $username;
        }

        public function getEmail() {
                return $this->email;
        }

        public function setEmail($email) {
                $this->email = $email;
        }

        public function getPassword() {
                return $this->password;
        }

        public function setPassword($password) {
                $this->password = $password;
        }
}

The Form

// My/Forms/Register.php
namespace My\Forms\Register;
use Spiffy\Dojo\Form;

class Register extends Form
{
        /**
         * (non-PHPdoc)
         * @see Zend_Form::init()
         */
        public function init() {
                $this->setName('register');
                $this->add('username');
                $this->add('email');
                $this->add('password', 'PasswordTextBox');
                $this->add('submit', 'SubmitButton');
        }

        /**
         * (non-PHPdoc)
         * @see Spiffy.Form::getDefaultOptions()
         */
        public function getDefaultOptions() {
                return array('entity' => 'Blitzaroo\Entity\User');
        }
}

The Controller

// application/controllers/RegisterController.php
use My\Forms\Register;

class RegisterController extends Zend_Controller_Action
{
        public function indexAction() {
                $form = new Register();
                $request = $this->getRequest();

                if ($request->isPost()) {
                        if ($form->isValid($request->getPost())) {
                                // success!

                                // user entity
                                $user = $form->getEntity();

                                // outputs the value of $form->username
                                echo $user->getUsername();
                        }
                }

                $this->view->form = $form;
        }
}

Wrap Up

Well, there’s a small example of what you can do with the new classes. This is not an exhaustive example nor have all the features (Filters) been implemented. Enjoy!

Rendering Dojo Stylesheets with a view helper

Tuesday, October 26th, 2010

I’ve been fervently coding Blitzaroo the passed week and I ran into a rather annoying issue when using AJAX with the Zend Framework and Dojo. Take, for example, using AjaxContext to load content for a dijit.layout.TabContainer that houses several dijit.layout.ContentPane(s).

$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContexts(array(
    'overview' => 'html',
    'events' => 'html',
    'members' => 'html',
    'recruits' => 'html'))->initContext();

Now then, when the getHref() from a ContentPane is called they load the Ajax data which, in this case, happens to be a dojox.grid.DataGrid. The grid renders just fine without Ajax but when Ajax is used ZF fails to load the proper Stylesheets which need to be loaded manually. I thought, no big deal, I’ll just hit up $this->dojo()->{some method to spit out stylesheets} and to my dismay found that the method is protected. Why? I’m not quite sure. I went ahead and wrote a view helper to fix the problem which is merely a copy/paste of the _renderStylesheet() method but without requiring the Dojo container object. If there is another way around the issue I’m all ears!

class My_View_Helper_DojoStylesheets extends Zend_View_Helper_Abstract
{
        public function dojoStylesheets()
        {
                $dojo = $this->view->dojo();
                $isXhtml = $this->view->doctype()->isXhtml();
                
                if ($dojo->useCdn()) {
                        $base = $dojo->getCdnBase() . $dojo->getCdnVersion();
                } else {
                        $base = $dojo->_getLocalRelativePath();
                }
                
                $registeredStylesheets = $dojo->getStylesheetModules();
                foreach ($registeredStylesheets as $stylesheet) {
                        $themeName = substr($stylesheet, strrpos($stylesheet, '.') + 1);
                        $stylesheet = str_replace('.', '/', $stylesheet);
                        $stylesheets[] = $base . '/' . $stylesheet . '/' . $themeName . '.css';
                }
                
                foreach ($dojo->getStylesheets() as $stylesheet) {
                        $stylesheets[] = $stylesheet;
                }
                
                if ($dojo->registerDojoStylesheet()) {
                        $stylesheets[] = $base . '/dojo/resources/dojo.css';
                }
                
                if (empty($stylesheets)) {
                        return '';
                }
                
                array_reverse($stylesheets);
                $style = '';
                
                return $style;
        }
}

Now my {action}.ajax.phtml script is nice and happy.

// call the regular members action page - no need to duplicate code!
echo $this->render('team-manager/members.phtml');

// inlineScript contains all the formatters for the grid
echo $this->inlineScript();

// New view helper to include the data grid CSS files generated by my DataGrid view helper
echo $this->dojoStylesheets();

Thursday, March 18th, 2010

I finally created a Google Code project for all my source code. You can find it at http://bit.ly/bgVXTq.