Leaking Abstraction

Loosely coupled thoughts on web development

Archive for January 2010

Running scripts in Zend Framework

leave a comment »

It’s always been a bit confusing to me where and how to execute scripts within my Zend Framework applications. Often times I would just initialize the autoloader and the classes myself in the script file itself.  Since the existence of Zend_Application, this has become a whole lot easier.

First, I create a folder called “scripts” in my application directory. This is an ideal location for scripts because it’s outside of the Apache HTTP root which means we don’t need to worry about remote execution. We can also easily point CRON jobs to this location instead of running some fangled CRON job to cURL a particular URL (Yes, I’m guilty of this, sadly).

Now, at the top of any script we write, add the following:

File: /application/scripts/anyscriptyouwrite.php
[ccew_php]
define(‘APPLICATION_ENV’,'script’);
require_once(‘../../httpdocs/index.php’);
[/ccew_php]

This sets our application environment to the “script” environment. Now, we will customize our Bootstrapper when running scripts by editing the index.php in the web root:

File: /public/index.php
[ccew_php]
if (APPLICATION_ENV == ‘script’) {
$application->bootstrap(‘Db’);
$application->bootstrap(‘Registry’);
/* ..etc.. */
} else {
$application->bootstrap()
->run();
}
[/ccew_php]

Notice, we don’t ever call the run() method, so the front controller never gets instantiated. This allows us to explicitly declare each resource we want to setup an environment more ideal for scripting.
Another cool side effect of using the APPLICATION_ENV is we can specify script-specific settings in our application.ini:

File: /application/configs/application.ini
[ccew_php]
[script : production ]
resources.db.adapter = PDO_MYSQL
resources.db.params.host = “hostname”
resources.db.params.username = “username”
resources.db.params.password = “password”
resources.db.params.dbname = “dbname”
[/ccew_php]

Written by Andy Baird

January 30, 2010 at 6:10 pm

Posted in Tutorials

Tagged with , ,

Resources for Zend Framework

with 2 comments

One of the most challenging aspects of the Zend Framework is that while there is a large volume of resources available for Zend Framework, sifting through this to get answers to specific problems can be tough. This is partially the fault of the nature of the framework — a very uncoupled library means there is a lot of ways to implement it, many of them undocumented.

If you dig deep enough, though, you’ll find that someone out there has probably tried to do whatever  it is you are trying to accomplish — or at least something like it. Here’s my list of the top resources I use to reach solutions for my Zend Framework problems.

  1. The Reference Guide – Duh, right? It’s #1 on my list, and it should be #1 on yours. If it isn’t, are you sure you’re reading it fully? I can’t tell you how many newbies I’ve talked to that simply have not read the appropriate reference guide section on the functionality they are asking about. It’s not perfect and it has some holes, but it is by far the most definitive resource.
  2. EDIT: As the much respected Matthew Weier O`Phinney points out in the comments, I’ve forgotten one of the best resources out there: The mailing lists. Take your pick or just sign-up to fw-general@. You may even end up with a reply from the author of the component you’re dealing with.
  3. Stack Overflow – Stack Overflow is a Q&A site full of knowledgeable developers. My favorite part about Stack Overflow is developers that otherwise have no concrete online identity such as a blog or twitter will respond to posts. There are many knowledgeable “lurkers” who come out of the wood-works and often have clever solutions to problems that I wouldn’t find on Google. Also, there are even some ZF contributors such as Bill Karwin who will personally respond to your questions.
  4. Surviving the deep end – After I read this, I could barely go back to my Zend apps in progress without completely restarting them from ground up. If MVC was ever unclear to you before reading this, read this now. Especially the section on controllers and models.
  5. Zend Framework in Action – Although intended for the Zend Framework 1.0 release, the concrete real-world examples it provides for some of the framework’s most core classes ([ccei_php]Zend_Controller[/ccei_php], [ccei_php]Zend_Auth[/ccei_php], [ccei_php]Zend_Acl[/ccei_php], [ccei_php]Zend_Db[/ccei_php]) is still relevant.
  6. IRC – This outdated protocol still thrives among hardcore developers, and PHP programmers are no exception. Join the #zftalk channel and ask your question. There are usually attentive and experienced users there who have probably ran into the problems you’re facing. Several large ZF contributors also lurk here as well.
  7. Twitter – I’ll admit, it’s not my cup of tea but it’s been a great resource for others. Ask your question, throw on the #zf hash tag, and cross your fingers.
  8. Blogs. Although most of the relevant ones will popup in a Google search, there’s a couple I subscribe to regularly (that you can see on my links section to the right). If it’s on my blogroll, it’s because I feel any new post they make will be relevant and insightful. Each one is worth checking out.
  9. and last but not least… nothing explains the code in more detail than the code itself. One of the most important lessons you can ever learn in programming is nothing teaches you like diving into the code yourself.  Although the task can seem daunting at first, it’s often a better solution than an endless Google search or waiting for answer.


Anyways, hope this helps someone. Maybe eventually this site can be added to the list above !

Written by Andy Baird

January 9, 2010 at 2:49 am

Posted in Articles

Tagged with ,

Zend_Db: query(), fetch methods, and Zend_Db_Select

leave a comment »

[cci_php]Zend_Db[/cci_php] provides several methods for querying a database. They range from a simple query wrapper to programmatically. Say we have database object [cci_php]$db = Zend_Db_Table::getDefaultAdapter()[/cci_php]:

query() – Will return the results of any SQL query.

fetchRow() – Will return only the first row of the result set.

fetchCol() – Will return only one column (the first one if your select statement will be used) as an array.

fetchOne() – Will return only the value of the first column of the first row of the query.

These methods return row objects wherever possible (for query(), fetchRow(), and fetchCol()). You can change this to an array by setting the fetch mode before executing the SQL:

[ccew_php]
$db->setFetchMode(Zend_Db::FETCH_ARRAY);
[/ccew_php]

Or, if you just want to get your results as an array in the first place, you can use [ccei_php]$db->fetchAssoc($query)[/ccei_php].

Creating queries programmatically with Zend_Db_Select

A [ccei_php]Zend_Db_Select[/ccei_php] statement produces SQL that is correct based on the adapter you are using. It also takes care of things you probably don’t ever bother to do when you write your own queries, such as deliberately expressing all tables along with their columns and properly escaping all table and column names. [ccei_php]Zend_Db_Select[/ccei_php] ultimately returns this query, so usage is simple:

[ccew_php]
$db->fetchRow($db->select()->from(‘sample’));
[/ccew_php]

In this case, [ccei_php]$db->select()->from(‘sample’)[/ccei_php] returns the following string:

[ccew_sql]
SELECT `sample`.* FROM `sample`
[/ccew_sql]

We can add parameters to our select statement easily:

[ccew_php]
$select = $db->select()->from(‘sample’);
$select->where(‘id=100′);
$select->order(‘id DESC’);
[/ccew_php]

Which produces:

[ccew_sql]
SELECT `sample`.* FROM `sample` WHERE (id=100) ORDER BY `id` DESC
[/ccew_sql]

With a little more research, you will quickly discover that you can perform nearly any non-complex query with [ccei_php]Zend_Db_Select[/ccei_php].

When to use Zend_Db_Select and writing SQL directly

The first thing you probably took away from Zend_Db_Select (at least I did) is the fact that it makes writing really simple queries way more complicated than they should be.

And, well, you’re right. It’s hard to fight the instinct that using Zend_Db_Select feels like the right thing to do – it feels like it’s the convention that a good programmer is supposed to follow. The reality is, for your application, you probably don’t need to use it. Here’s the list of conditions I came up with where I use Zend_Db_Select over writing the query directly.

  • You are writing an application that needs to run on top of different types of RDBMS?
  • You are writing a piece of code that you want to use in several different applications where the environments are unknown.
  • You are writing a query that will be modified based on different logic conditions.

For the average application, you probably won’t find yourself needing Zend_Db_Select that much. That said, when you do need it, nothing can beat it for the level of abstraction it provides.

Written by Andy Baird

January 9, 2010 at 1:36 am

Posted in Tutorials

Tagged with ,

Using Zend_Db standalone

leave a comment »

If there is one class I had to pick out of the ZF library as the crown jewel, it would without a doubt be Zend_Db.
I rarely touch a PHP application or script that interacts with any database without utilizing this class.

Let’s go over the quick list of why it’s my fave:

  • It automatically wraps PDO extensions and normalizes them as best as possible across different types of databases (in simple terms: change from a MySQL database to an MS SQL or PostgreSQL database with minimal code change)
  • It sanitizes data input for you automatically (as long as you use it correctly)
  • You can quickly grab results in array or object form without performing any post query operations.
  • Provides methods for programatically creating queries

On top of that, it’s easily decoupled from the rest of the library. Let’s start out by ripping out Zend/Db.php and the Zend/Db folder and dropping it in our app.

Initializing the database connection

Now, in our settings / boilerplate file let’s initialize the database adapter. The database adapter uses a lazy connection (meaning it doesn’t actually connect to the database until you perform a query with it) by default. This makes the application settings a perfect place to setup our database object.

[ccew_php tab_size="4"]
$db = Zend_Db::factory('Pdo_Mysql', array(
	'host'             => 'localhost',
	'username'         => 'database_username',
	'password'         => 'database_password',
	'dbname'           => 'database'
));
[/ccew_php]

That’s easy enough. If the application is simple and you plan on referencing the $db variable every time you want to make a query, you can stop right there. If you plan on using the database connection within a function or class scope, you don’t have to re-initialize it every time (or use icky global variables). Zend_Db_Table comes with a static function for setting the default database adapter.

[ccew_php]
require_once('Zend/Db/Table.php');
Zend_Db_Table::setDefaultAdapter($db);
[/ccew_php]

And now within our classes or functions, we can easily call it at any time:

[ccew_php]
class MyClass {
	private $db;
	function __construct() {
		$db = Zend_Db_Table::getDefaultAdapter();
	}
}
[/ccew_php]

Presto. Persistent database object any time we need it in our application / script.

Written by Andy Baird

January 5, 2010 at 4:01 pm

Posted in Tutorials

Tagged with ,

Hacking Geshi syntax highlighter to recognize Zend Framework classes

leave a comment »

This is kind of off-topic, but pretty neat. I was able to modify my Geshi WordPress plugin (called CodeColorer) to recognize Zend classes and link to the proper ZF Manual page. Example:

[cc_php]
//Example of automatic Zend_ class linkage!
Zend_Acl Zend_Amf Zend_Application Zend_Auth Zend_Cache
Zend_Captcha Zend_CodeGenerator Zend_Config Zend_Config_Writer Zend_Console_Getopt
Zend_Controller Zend_Currency Zend_Date Zend_Db Zend_Debug
Zend_Dojo Zend_Dom Zend_Exception Zend_Feed Zend_File
Zend_Filter Zend_Form Zend_Gdata Zend_Http Zend_InfoCard
Zend_Json Zend_Layout Zend_Ldap Zend_Loader Zend_Locale
Zend_Log Zend_Mail Zend_Measure Zend_Memory Zend_Mime
Zend_Navigation Zend_OpenId Zend_Paginator Zend_Pdf Zend_ProgressBar
Zend_Queue Zend_Reflection Zend_Registry Zend_Rest Zend_Search_Lucene
Zend_Server Zend_Service Zend_Session Zend_Soap Zend_Tag
Zend_Test Zend_Text Zend_TimeSync Zend_Tool_Framework Zend_Tool_Project
Zend_Translate Zend_Uri Zend_Validate Zend_Version Zend_View
Zend_Wildfire Zend_XmlRpc ZendX_Console_Process_Unix ZendX_JQuery
[/cc_php]

It wasn’t too tough to do either. Replace your Geshi library with this one or, if you want to use the same WordPress plugin as I’m using, download the entire CodeColorer plugin and extract to your WordPress plugins directory.

Note: I probably have not added all Zend class documentation links – I didn’t recurse through the whole ZF library and add every class because most actually don’t have a dedicated manual section. In most cases I only added the main parent class. I’ll try to keep this as updated as possible with new ZF releases.

Last file update: January 5th, 2010

Download CodeColorer WordPress plugin
Download only Geshi library

Written by Andy Baird

January 5, 2010 at 3:43 pm

Follow

Get every new post delivered to your Inbox.