Logging in Users using Doctrine and Zend_Auth

Jon Lebensold publishes the second part of his series on using Doctrine in combination with Zend_Auth & Zend_Auth_Adaptor; Here’s the second part of my Doctrine / Zend_Auth example. In 15 minutes, we create a logout, login and protected area that’s reliant on the ZC_Auth_Adapter adapter we created in last week’s video. Notice how there’s no code in the IndexController exposing the authentication implementation,

Grab a copy of the project or browse the repository.

Check it out here; Zendcasts.

Writing a Zend_Auth_Adapter with Doctrine

Jon Lebensold publishes another installment of his popular screen cast series, he writes; I’ve been using Doctrine a lot in my own work, and recently found myself itching to have tighter integration between Zend and Doctrine when it comes to user logins. Luckily, Zend provides a very simple interface with regards to Zend_Auth. This way, it’s easy to decouple your persistence layer (in my case Doctrine) from the authentication layer. I’ve borrowed from Palo Verede’s wonderful article on Doctrine and Zend_Auth and I invite you to check his blog out.

Grab a copy of the project or browse the repository.

Look at the video and comment here;  Zendcasts.

Test Results on Memory Usage of Zend Framework and Doctrine with APC

A few interesting observations made by rvdavid; After investigating a recommendation to use Doctrine by a fellow blogger, Brian at Real of Zod, I have decided to run with Doctrine as my Domain Model in Zend Framework projects. The thing is, if I’m going to commit to this, I need to know that applications I build in the future with the Zend Framework while using Doctrine as an integral part of the Model layer will not take performance hits from things like memory usage.

With Doctrine doing a _lot_ of magic, I thought that this would be something that I wanted to see for myself.

4MB Memory to execute a simple Query?!?! Ffffff#$#!!!!

A quick google search took me to a Question posted on StackOverflow about Doctrine Memory Usage. The concerned OP was asking if he had a server misconfiguration or if this was normal for Doctrine to be using so much memory for a simple query. He posted a 4MB difference in Peak Memory Usage between the start of the request before the Doctrine Query was executed and after the Doctrine Query was executed. After reading that, I was a little nervous.

Use Opcode Caching to reduce Memory Usage.

via » rvdavid: A Web Developer’s Blog.

Deep Integration between Zend Framework and Doctrine 1.2

There’s been a lot of talk online about finding the best approach for bringing Zend Framework and Doctrine 1.x together. This video is my humble approach of combining some of the learning brought about over the last few weeks on Zendcasts, as well as suggestions from Doctrine developers.

The goal of this video is to show how you leverage the existing resource loading tools in Zend to have a model structure that reflects Zend’s best practices. This video builds on the last Doctrine video, but if you’re familiar with both frameworks, you should be able to follow along. Enjoy!

via Deep Integration between Zend and Doctrine 1.2 | free Zend Framework screencasts – Zendcasts.

Setting Up Doctrine for Zend Framework 1.9.x

After some fiddling and googling and Zendcast watching 🙂 I figured out how to get the models to generate the way I needed them to.
And figuring out why generate-sql and build-all-reload did not create sql schema nor create any tables in the mysql database.

Directory Structure

Standard ZF directory structure with a few addition (Can’t wait for ZFTool to do all this for us)

├───application
│   ├───configs
│   │   ├───data          < --
│   │   │   ├───fixtures <--
│   │   │   └───sql        <--
│   │   └───migrations  <--
│   ├───controllers
│   ├───models
│   ├───scripts            <-- doctrine.php & bat here
│   └───views
├───library
│   ├───Doctrine        <-- Please use the latest 1.2.x
│   ├───vendor         <-- Do not forget this one or things will be bad.
├───public

 

application.ini

Only applicable parts added.
[production]
phpSettings.date.timezone = "Europe/Stockholm"
autoloaderNamespaces[] = "Doctrine"
doctrine.dsn = "mysql://root@localhost/testbench"
doctrine.data_fixtures_path = APPLICATION_PATH "/configs/data/fixtures"
doctrine.sql_path = APPLICATION_PATH "/configs/data/sql"
doctrine.migrations_path = APPLICATION_PATH "/configs/migrations"
doctrine.yaml_schema_path = APPLICATION_PATH "/configs/schema.yml"
doctrine.models_path = APPLICATION_PATH "/models"

Bootstrap.php

Please note the inline comment about model loading attributes, this is what broke it for me, for some reason using conservative will prevent generation and creation of database tables and schemas, although model generation works fine, very puzzling!.

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap {

protected function _initDoctrine() {
$this->getApplication()
->getAutoloader()
->pushAutoloader ( array ('Doctrine', 'autoload' ) );
//spl_autoload_register ( array ('Doctrine', 'modelsAutoload' ) );
$manager = Doctrine_Manager::getInstance ();
$manager->setAttribute ( Doctrine::ATTR_AUTO_ACCESSOR_OVERRIDE, true );
// The Model Loading acts a tad weird - Use Default for now.
//$manager->setAttribute ( Doctrine::ATTR_MODEL_LOADING, Doctrine::MODEL_LOADING_AGGRESIVE); // MODEL_LOADING_CONSERVATIVE
$manager->setAttribute ( Doctrine::ATTR_AUTOLOAD_TABLE_CLASSES, false );

$doctrineConfig = $this->getOption('doctrine');
$conn = Doctrine_Manager::connection($doctrineConfig['dsn'],'doctrine');
$conn->setAttribute(Doctrine::ATTR_USE_NATIVE_ENUM,true);

}
}

doctrine.bat

Since this dev machine is on Windows XP:
@echo off
echo Running Doctrine CLI.
"C:\Zend\ZendServer\bin\php.exe" -f C:\Zend\Apache2\htdocs\testbench\application\scripts\doctrine.php %1 %2 %3 %4 %5 %6 %7 %8 %9

doctrine

If you are linux/mac based: (Dont forget to chmod +x it)

#!/usr/bin/env php
< ?php chdir(dirname(__FILE__)); include('doctrine.php');

doctrine.php

Please note the inline comments in this one and customize it to your own liking.

< ?php /** * Doctrine CLI */ error_reporting(E_ALL); define('ROOT_PATH', realpath(dirname(__FILE__))); define('APPLICATION_PATH', realpath(dirname(__FILE__) . "/../")); define('APPLICATION_ENV', 'development'); //Ensure library/ is on include_path set_include_path(implode(PATH_SEPARATOR, array( '../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' ); // Read in the application.ini bootstrap for Doctrine $application->getBootstrap()->bootstrap('doctrine');

// Create the configuration array
$config = $application->getOption('doctrine');
// (Note you can have all of these in application.ini aswell)
$config['generate_models_options'] = array(
// Define the PHPDoc Block in the generated classes
'phpDocPackage' =>'TestBench',
'phpDocSubpackage' =>'Models',
'phpDocName' =>'Danny Froberg',
'phpDocEmail' =>'[email protected]',
'phpDocVersion' =>'1.0',
// Define whats what and named how, where.
'suffix' => '.php',
'pearStyle' => true,
'baseClassPrefix' => 'Base_',
// Unless you have created a custom class or want Default_Model_Base_Abstract
'baseClassName' => 'Doctrine_Record',
// Leave this empty as specifying 'Base' will create Base/Base
'baseClassesDirectory' => NULL,
// Should make it Zend Framework friendly AFAIK
'classPrefix' => 'Default_Model_',
'classPrefixFiles' => false,
'generateBaseClasses' => true,
'generateTableClasses' => false,
'packagesPath' => APPLICATION_PATH . '/models',
'packagesFolderName' => 'packages',

);

$cli = new Doctrine_Cli($config);
$cli->run($_SERVER['argv']);
?>

In the next article we'll take it for a test spin and generate a few models and such 😉

Enjoy.

Generate Doctrine models/classes that extend a custom record class

When using using Doctrine 1.2.1 and Zend Framework 1.9.x to generate classes from Yaml/db each Base class (which includes the table definition) extends the Doctrine_Record class.

I need to find a way of telling Doctrine to extend my own Base class, or find a different solution to a master/slave db setup using Doctrine.

Example generated model:

abstract class My_Base_User extends Doctrine_Record
{

However I need it to be automatically generated as:

abstract class My_Base_User extends My_Record
{

And the answer is (drumroll)

Typical, as soon as I ask the question I manage to find the answer. I’m recording it here in case anyone else has the same issue.

You can pass in the parameter ‘baseClassName’ into the generateModels* methods and Doctrine will use that as the Base record class.

Examples:

Doctrine_Core::generateModelsFromDb('models', array('master'), array('generateTableClasses' => true, 'baseClassName' => 'My_Record'));

or using Cli:

$options['generate_models_options'] = array(
'pearStyle'             => true,
'baseClassPrefix'       => 'My_',
'baseClassName'         => 'My_Record',
'classPrefix'           => '',
'classPrefixFiles'      => false,
'generateTableClasses'  => true,
);
$cli = new Doctrine_Cli($options);

Object-relational mapping with Doctrine, Flash Builder, and PHP

Richard Bates @ Zend Developer Zone wrote a good article on my favorite ORM Doctrine integration in Zend;

Rich Internet applications built with Adobe Flex and Flash Builder have been steadily gaining a foothold in enterprise development for quite some time. As the platform has grown and evolved, PHP has also made amazing progress toward becoming a mature, powerful object-oriented language with rapid adoption and dozens of frameworks and design pattern implementations. As PHP continues to prosper, developers are able to borrow more and more of the things Java has got right, taking one check after another from the “Java-only” column. One outstanding example of this is object-relational mapping (ORM). A few different PHP ORM implementations are available, and all of them have positive attributes. However, after some experimentation, I’ve found that Doctrine is my favorite.

Read the complete story;

Object-relational mapping with Doctrine, Flash Builder, and PHP.