Setting Up Zend Framework 2 Autoloader

May 13th, 2014

If you’re like me, you like to dig into the belly of things and twist them to your own uses. Tonight, I’ve been monkeying around with ZF2 autoloaders, and working out how they function.

I store my ZF install in a dir (Zend/) in my include path, so I don’t have to maintain copies for each site on my server.

Some useful notes on this:

The stock ZF2 download does not include a pre-generated classmap file. To generate this, go into the default unpacked archive folder, into bin/ and run this command:

php classmap_generator.php -l "/usr/share/php/Zend/"

[code language=”php”]
// How to get an absolute path to the generated classmap file (return: /usr/share/php/Zend/autoload_classmap.php)
$classmapPath = stream_resolve_include_path(‘Zend/autoload_classmap.php’);

// How to get the autoload up and running
require_once ‘Zend/Loader/ClassMapAutoloader.php’;
$autoloader = new Zend\Loader\ClassMapAutoloader();

That’s all for tonight folks!

Which Framework?

July 21st, 2013

Learning a framework is an investment of time. You have to work out how this one structures its files, wants you to template, what levers to pull.

This is why people build their own so often. At least then it works the way you want it to.

composer more.json

July 17th, 2013

So tonight, more fun with composer. Now that I have it set up and managed to install one package, it’s on to getting enough of Zend Framework set up to make something. Since there seems to be no core package that just installs everything, it seems I have to resort to listing the arms length of packages I expect to use.

Scratch that. Tonight I’m going to try out the ZF2 skeleton application, since I haven’t used ZF2 yet.

Lessons Learned From framework – A Dissection

June 4th, 2010

For the last two and a half years or so, I have spent time off and on working on a framework for my websites. There were a lot of reasons that I was doing this, but the main two were I didn’t like the frameworks that were out at the time, and I wanted to learn some cool new code.

So, here we are, a long time later, and I’ve decided to start from near scratch on a new version. Before I embark on that challenge though, I’m dissecting what I have learned through the process, so hopefully someone can learn at least one thing.

1. URL Rewriting
How you write URL’s is the subject of so many articles on the internet about SEO and other things that I won’t really get into it. Needless to say, it’s important to have useful and clear URL’s.

Processing those URL’s
This is one of the cool tricks I started working with. mod_rewrite rules are really cryptic (regex is cryptic), so I made it simple. Assuming you are using Apache, use this rule in your .htaccess, then never have to screw around with it again.

[code]RewriteEngine On
RewriteRule !\.(js|ico|gif|jpg|png|css|pdf|swf)$ @yourawesomescript.php[/code]

This points all visited URL’s to your main script. Once there, dissect the URL with the following code, and process however you want.
[code lang=”php”]
$route = $_SERVER[‘REQUEST_URI’];
$base_script = CONFIG_BASE_SCRIPT_NAME; // This should be your base script URL aka /framework/@yourawesomescript.php

for($x = 0, $c = strlen($base_script); $x < $c; $x++){
if(strtolower(substr($base_script, 0, 1)) == strtolower(substr($route, 0, 1))){
$route = substr($route, 1);
$base_script = substr($base_script, 1);

$route = explode(‘/’, $route);
$appControl = (isset($route[0]) && !empty($route[0])) ? array_shift($route) : ‘index’;
$appAction = (isset($route[0]) && !empty($route[0])) ? array_shift($route) : ”;
$appVars = (!empty($route)) ? $route : array();

2. Zend Framework Is Awesome!
Zend has started a project that saves so much time. The ZF is not just a framework though. Because the components are loosely coupled, you can pick and choose what you want to use as part of your project, and toss the rest. This is a huge time saver simply because it is code that you do not have to maintain.

Here’s a sample database query. Nice and clean, and Zend_DB handles both building the query (including escaping the data) and running it.
[code language=”php”]
$userconf = $db->fetchAll(
->from($config->dbschema->table_users, array(‘uid’))
->where(’email = ?’, $in[’email’])
->where(‘actkey = ?’, $in[‘cid’])

3. minify Is Also Awesome
If you are not using minify, you should be.

It combines multiple CSS or Javascript files, removes unnecessary whitespace and comments, and serves them with gzip encoding and optimal client-side cache headers.

The best reason for using minify is that you can take the 5 or 6 Javascript files you might be serving, and group them into one nice little package. You will never have to upload pre-compressed scripts to your server, and you can still serve them all compressed (gzip and packed) and optimized with one URL (1 HTTP request instead of several):

[code]<script type="text/javascript" src="min/g=js&1"></script>[/code]

And, to save you more time, here is a sample groupsConfig.php file (reference file system layout at the bottom of this article):
[code language=”php”]

$mingc_base_url = ‘/framework’;
$mingc_base_layout = $mingc_base_url . ‘layout/’;

return array(
‘js’ => array(
$mingc_base_layout . ‘js/jquery.lightbox.js’,
$mingc_base_layout . ‘js/DD_roundies.js’,
$mingc_base_layout . ‘js/base.js’,
‘css’ => array(
$mingc_base_layout . ‘css/main.css’,
$mingc_base_layout . ‘css/jquery.lightbox.css’,

4. Output Buffering For Amazing Awesomeness
Output buffering will save you a lot of hassle. You can pass headers at any point in your script simply by turning this on. This means that you can do things like redirecting users to another page without having to show them any content (which saves you a little hassle as a dev, and them a little time). And speaking of redirecting, that leads me into:

5. Shortcircuit The Problem (redirect_hard)
Not every page you load needs to show content. Some just need to process what you post from a form, or check if someone is logged in, or just bounce you somewhere else in a site. For these times, I have a function that I use that sends a Location: header directly to the browser, telling it to go away to somewhere else.

[code language=”php”]
function redirect_hard($url = null, $internal = 1){
// CONFIG_HREF_SITE is defined as
header(‘Location: ‘ . CONFIG_HREF_SITE . $url);
header(‘Location: ‘ . $url);

6. Exceptions Are Better Errors
I have seem (and written) a lot of code that handles errors in a strange way.
[code language=”php”]
$err = 0;

if($x != 4){$err = 1;}
if($y != 2){$err = 1;}

if($err){echo ‘Error’; break;}else{echo ‘Happy ‘ . ($x + $y);}

There is a better, and way more awesome way to do this. Exceptions are much easier and cleaner to work with, because you can just wrap a big piece of dependent code with one big exception handler, and go to town on whatever you want to do. Here is the same functionality as above, with exceptions:

[code language=”php”]
if($x != 4){throw new Exception(‘x is not set!’);}
if($y != 2){throw new Exception(‘y is not set!’);}
// If either condition is not met, and an exception is thrown
// then the code below here is not executed.
echo ‘Happy ‘ . ($x + $y);
}catch(Exception $e){
echo ‘Error: ‘, $e->getMessage(), "\n";

Now, of course, it looks a little more complicated in this small example, but imagine if you had a half-dozen events that you were executing that could throw an error. With exceptions, your execution of that particular try{}catch{} block would stop as soon as one of these events occurred, and you would know precisely where. Learn and love exceptions and exception handling, because it will save you a lot of mess.

7. Components Are So Generic
You have a form that you use for both adding and editing a food, for example. Well, you could build the form once, then copy-paste it into the two places where you will use it. Of course, then you need to make sure that when you make changes, they stay in sync. Easy enough if you only have a form in two places. Imagine though, that you have a form that you use in a half-dozen places.

Make it into a component, because less code is always easier to maintain. Below is a wrapper component that I use around every form I create. All I have to do is make sure that I set the form URL and content, then include this piece of code. It doesn’t seem like much, but now, I have removed 6 lines of HTML from every form I create, and I have a centralized control over the form.

[code language=”php”]
$page_content .= ‘
<div class="center_div">
<form action="’ . $form[‘url’] . ‘" method="post">
‘ . $form[‘content’] . ‘

If you have a piece of complex code in more than two places, do this instead.

8. Have A Config File
This is a simple lesson. Never put any variable that relates to any configuration anywhere but in this file. Database settings, the constant for PI, the name of your website, they all go here. Everything is so much easier when the only change between your production and development environment is your config file.

9. Hold The Mail
I have seen a lot of approaches to mail. Some say fork it, some say send it and make the user wait. I have a more interesting solution. I built a mailqueue script. What happens when I want to send email is it gets placed in a database. There is a script attached to a cron job (a task on a timer), and it is called every 5 minutes. The only thing this script does is check the database and send the email sitting in the queue. The benefits of this are:

  1. I don’t have to make a user wait (hitting a database will likely always be faster than sending an email on a high load server)
  2. Email sent can now be logged
  3. All sending on the backend can be taken care of in a speedier language (perl or c)
  4. I have precise control over how much mail is processed in a day, so I can throttle it as needed

Classes Are Classier
Again, another topic that has been written about extensively. Here is the shortlist of why I find classes awesome.

  • Everything is accessible through one discreet interface ie $db->connect, $db->select()
  • Once it’s written, it’s easy to maintain and expand, and still all through that one interface
  • You can move it so much easier
  • No mucking around with variables that you need to keep track of ($age, $height, $weight can all be inside $person, so you can $person->get(‘age’))

I hope that all this information is useful to someone else, and if you have any comments, feel free to let them be heard.

Reference Filesystem Layout
/framework/@yourawesomescript.php <--- Base script /framework/min/ <--- minify directory /framework/layout/ /framework/layout/js/ /framework/layout/css/

WordPress - Entries (RSS) and Comments (RSS) - © 2011 Ben Dauphinee