Category Archives: PHP

Getting Smarty 3.0 to work with Zend Framework 1.9

Assuming you’re using the method demonstrated in the Zend Framework Manual, the first thing you need is to configure the Zend AutoLoader. Add this to the index.php file in your public directory:

// Configure autoloader
require_once 'Zend/Loader/Autoloader.php';
$autoloader = Zend_Loader_Autoloader::getInstance();

// Require Smarty Engine
require_once 'Smarty/Smarty.class.php'; // Assuming that you have the Smarty engine at "library/Smarty"
$autoloader->pushAutoloader('Smarty', 'smartyAutoload');

Change the following line in “Smarty/Smarty.class.php” (about line 91) from this:

if (set_include_path(SMARTY_SYSPLUGINS_DIR . PATH_SEPARATOR . get_include_path()) !== false) {

To this:

if (!class_exists('Zend_Loader_Autoloader') && set_include_path(SMARTY_SYSPLUGINS_DIR . PATH_SEPARATOR . get_include_path()) !== false) {

Next, comment out the line in the Smarty Constructor (about line 237):

//$this->template_dir = array('.' . DS . 'templates' . DS);

We want to keep it a null value (which is the default). If we don’t make this change in the constructor (mentioned just above), we’ll get PHP Notices that Zend_Controller_Action_Helper_ViewRenderer tried to convert an array to a string.

Finally, add this to your bootstrapper class:

protected function _initView()
{
$viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper(‘ViewRenderer’);
$view = new Zend_View_Smarty();

$viewRenderer->setView($view)
->setViewScriptPathSpec(APPLICATION_PATH . ‘/views/scripts/:controller/:action.:suffix’)
->setViewSuffix(‘tpl’);
}

If you’re using modules, you might want to make a slight change to the setViewScriptPathSpec method:

setViewScriptPathSpec(APPLICATION_PATH . ‘/modules/:module/views/scripts/:controller/:action.:suffix’);

You should be good to go. I should mention that this will cause your layouts to be parsed via Smarty as well; which presents its own problems. A potential work around is to include a common header and footer for each individual template, although this is far from ideal. In that case, what you might want to do is disable the view renderer’s auto render feature and create a custom plugin or action helper that will render the templates and layouts. I’m considering expounding on this in another post…

Zend Framework Migration and File Not Found

Recently I went through and upgraded a website from Zend Framework 1.7 to the latest 1.9 minor version. Everything worked great for the most part (aside from a minor code change involving Zend Filter for requests), but there was one significant change that was a bit of a hassle to fix (i.e. “File not found” and “directory listings prohibited” Apache errors).

One of the major changes since 1.7 is the functionality of the Zend Framework class AutoLoader. In previous versions of Zend Framework all you had to do was instantiate the AutoLoader and the classes would magically load as needed. But now it’s not quite so simple. The rationale, and it’s quite good, for the change can be read about in this Zend devzone article.

It’s important to mention at this point that if, for examle, your “IndexController” inherits directly from “Zend_Controller_Action”, you will not need to do any of this because in that scenario, you should not have any of these issues. These hurdles are only applicable if you extend the Zend Framework classes with your own.

Moving on… Instead of just instantiating the AutoLoader, you must now declare all namespaces that will be used throughout your application. For example, in your application controllers directory you might have a class named “BlogController.php” and your class would be named something like “IndexController” which extends a custom controller in the library that looks like “Blog_Controller_Action” and that class would extend “Zend_Controller_Action”. The AutoLoader knows where to find “Zend_Controller_Action”, but it doesn’t know where to look for “Blog_Controller_Action”. There are two solutions to this problem.

The easy answer is you to add the “$autoloader->setFallbackAutoloader(true);” function call, but this is kind of hack. In addition, using the Zend Framework default loader as a fallback means that every request to your site will result in an error, and then Zend Framework will try to use the default loader to resolve the request. This means extra load time and extra stress on the server. Granted, there is an “$autoloader->suppressNotFoundWarnings(true);” function, but it doesn’t work the way you think. Read more about the default autoloader on the Zend Framework manual here.

The correct solution to this problem is to declare all your namespaces and instantiate a unique AutoLoader for your models and controllers. For example:

// Set up autoload.
require_once 'Zend/Loader/Autoloader.php';
$autoloader = Zend_Loader_Autoloader::getInstance();
$autoloader->setFallbackAutoloader(true);
// Just in case there's something we missed, we can leave the fallback

// Add resource loader, otherwise "file not found" errors are raised
$resourceLoader = new Zend_Loader_Autoloader_Resource(array(
    'basePath'  	=> '../library/Blog/',
    'namespace' 	=> 'Blog',
	'resourceTypes'	=> array(
		'model'			=> array(
			'path'		=> 'model/',
			'namespace'	=> 'Model',
		),
		'controller'	=> array(
			'path'		=> 'controller/',
			'namespace'	=> 'Controller'
		)
	)
));

$autoloader->pushAutoloader($resourceLoader);

You can read all the details here. It’s quite a change from the simplicity before, but it’s a good change.

In addition, you’ll need to make sure to update your .htaccess to the following or else you’ll get a bunch of “Directory indexes prohibited by server configuration” errors:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]

This also has been modified and improved over previous versions, for one, it loads Flash files (and other non-standard extensions) without a problem. Strangely, I didn’t see the .htacces directives in the Zend Quickstart tutorial, but it is in the Zend Framework’s manual Application Quickstart. The page names are similar but they are completely different.

In summary, until we made the changes mentioned above to our Zend Framework configuration our Apache error log was riddled with thousands of “File not found” and “Directory indexes forbidden” errors. The AutoLoader change resolved the “file not found” errors, and the .htaccess update resolved the “Directory indexes forbidden” errors. Hope this was useful.

Zend Framework on MediaTemple DV

I’ve done this a few times already, and it seems every time I make the same time-wasting mistakes. So here’s the process quick and dirty (be sure to follow the links if there’s a point you don’t understand or know how to do):

  • SSH into your website, navigate to your virtual host directory – the directory above the webroot (the one right above httpdocs) – this is the default directory when connecting via FTP.
  • Via SSH, create the necessary “application” and “library” directories above your webroot (same level as the httpdocs folder).
  • Via SSH, chmod 0777 the “application” and the “library” directories.
  • Download the Zend Framework and upload it to your recently created “library” directory above the webroot (easiest with ftp, or you could do it the harder way via wget).
  • Add your newly created “application” and “library” directories to your approved includes directories via open_basedir configuration on your virtual host. You should be adding something that looks like: “/var/www/vhosts/mt-example.com/library:/var/www/vhosts/mt-example.com/application” – pay attention to colon, :, placement.
  • Make sure you restart the server.

If you’ve never used Zend Framework before, you may want to follow along with the Quickstart from here.

If you’re going to using Flash, make sure to make the change in the .htaccess I mention here. Also, if you plan on uploading images at some point and would like MIME type validation and/or file information you’ll need to install the PECL fileinfo extension as explained by Jeffrey Barke on his website.

That’s it. Kind of a pain since you have to do this every time you set up a new site (domain or subdomain), granted you could probably put the framework higher in the operating system and just link to it, but that has it’s own problems (i.e. framework version support/maintenance) and it wouldn’t save you any steps. Anyway, hope this is as useful to someone else as I know it will be to me.

T_PAAMAYIM_NEKUDOTAYIM

Parse error: syntax error, unexpected ‘)’, expecting T_PAAMAYIM_NEKUDOTAYIM in …

I encountered this weird PHP error today; if it happens to you it’s probably because you forgot to declare a variable by leaving off the ‘$’ prefix (e.g., ‘myVar’ instead of ‘$myVar’). More info here: http://en.wikipedia.org/wiki/Paamayim_Nekudotayim.

Obviously, it’s a fairly cryptic error message; albeit its cause is simple to resolve. It is exactly these types of things that makes it easier to understand why so many developers dislike PHP – it doesn’t keep me from using it though.

Zend Framework & Flash

Here’s a quick little “gotcha” when using the Zend PHP Framework:

If you plan on using Flash at all (i.e., SWF or FLV files) be sure to append the necessary extensions the .htaccess file in the “public” folder to the rewrite rule:

RewriteEngine On
RewriteRule !\.(js|ico|gif|jpg|png|css|swf|flv)$ index.php

Note the added “swf” and “flv” extensions. Otherwise access to these files will return an error. Firebug (if you use it) will say that the files are being loaded (200 OK), but if you look at the response, it’s the error page not the actually requested file that is being returned.

Granted, this isn’t exclusive to the Zend Framework – it’s a result of the .htaccess configuration (regardless of which framework/engine you use); but it’s just something to keep in mind.

Update:

Here’s a better declaration (via: http://framework.zend.com/manual/en/zend.application.quick-start.html):

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]

Prado PHP 5 Framework

I’ve been reading a lot about ASP.Net (with C#) recently. I want to learn to use ASP.Net proficiently so that I can add it to my web “toolkit” (development languages I’m familiar with). A major downside to learning a new language is that as you consistently practice the new, it seems that you lose your grasp on what was once familiar – the old.

Fortunately, PHP and C# aren’t too different (not as dissimilar as PHP and VB anyway). But, ASP.Net itself (regardless of which language you use with it; VB or C#) is a component and event based framework, requiring certain rules and components to tie the back-end to the front-end (generally speaking). PHP, on the other hand, is not built this way; most PHP code is written inline. So when switching back-and-forth between developing in ASP.Net and PHP (or any multitude of languages), there are unique approaches that are required in accomplishing the same tasks. Obviously, this can become very confusing.

To get to the point: last week, I happened to come across the Prado PHP Framework. My first thought was, “Oh, another PHP framework”, but then I took a closer look at the syntax and the page rendering model. As I looked through the tutorials and documentation, it dawned on me that by using Prado I wouldn’t have to worry about using different approaches to server-side development. I could use the same model with ASP.Net and with PHP.

I immediately became excited at the possibilities. How simple would it be to develop and application in one language and port it to the other? If you’re already using the same model, all you would be switching is the “engine”. Anyway, before I digress too much (this post is already exceedingly lengthy) and ramble forever I’ll conclude with this: If you’re a PHP developer and interested in ASP.Net, or if you’re an ASP.Net developer interested in PHP, Prado is the way to go. Check it out at www.pradosoft.com.

Symfony Install and Setup for Windows XP with Apache 2.2

The following is a compilation of notes taken while installing and configuring Symfony for Windows XP with Apache 2.2:

The Process

  • Make sure that PHP is installed, then go to your PHP directory (i.e., C:\php) and double click go-pear.bat.
  • It will ask whether you would like to install a system-wide or local copy, type in “local” and press enter, it will ask you to confirm, type in “yes” and press enter.
  • You should see a list displaying a suggested file layout, press enter and continue.
  • The installer will ask if you would like to “alter php.ini” type in “Y” and press enter.
  • After the installer has completed, open up a command prompt window and go to the root directory (i.e., C:\). You can do this by typing: “cd \”.
  • From the command prompt type: “pear channel-discover pear.symfony-project.com” and press enter. It should tell you “Discover of channel “pear.symfony-project.com’ succeeded”.
  • Now to install symfony, type in:
Pear install symfony/symfony
  • You should see text that says “downloading symfony-1.0.6.tgz” and some loading progress, after the download is completed it will install symfony, and if everything goes well it will say “install ok”.
  • After the installation is complete, navigate to the directory in which you would like to initialize your first symfony project and make sure that it’s within your web root (e.g., C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\symfony).
  • When you’re in your target directory type:
symfony init-project myproject
  • You should see a dump of assets. When it’s complete, type in:
symfony init-app myapp
  • After this is complete, navigate to the directory into which you initiated your symfony project (e.g., C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\symfony) and verify that within the “web” directory that there is an “sf” folder, chances are that folder is nonexistent. You’ll need to navigate to C:\php\PEAR\data\symfony\web\ (or, in my case: C:\php5\pear\data\symfony\web\) and copy the “sf” folder from there into the “web” folder within your install directory. You should be good to go.

Apache 2.2, PHP 5, and MySQL 5 Install and Setup on Windows XP

The following is a series of notes that I compiled while installing and configuring Apache 2.2, PHP 5, and MySQL 5 on Windows XP:

Apache Installation

  • Download Apache HTTP Server (v2.2) from apache website or from mirror, make sure to get a binary file.
  • Run binary file and install Apache.

MySQL Installation

  • Download MySQL Server from dev.mysql.com, do NOT get “essentials” version.
  • It may ask you to login/signup, etc. Just click the link at the bottom: “No thanks, just take me to the downloads”.
  • Run binary and install MySQL.
  • (Optional) Check configuration box and edit configuration settings to your preference.
  • Make sure that MySQL is added to the BIN PATH.

PHP Installation

  • Download PHP 5, be sure to get the ZIP archive and NOT the installer.
  • Extract the archive to c:\php (or your preferred location).
  • After extraction is complete, copy php5ts.dll to C:\Windows\. Make a copy of php.ini-recommended and rename it to “php.ini”; move this file into your C:\Windows\ folder.

Apache Configuration

  • Open your httpd.conf file (C:\Program Files\Apache Software Foundation\Apache2.2\conf) and find the line that looks like:
DirectoryIndex index.html

Change to this:

DirectoryIndex index.html index.php

Feel free to add other extensions as well (e.g., index.htm, index.php5, etc.) if you wish.

  • Find the area in the httpd.conf file that lists the loaded modules (e.g., “LoadModule foo_module modules/mod_foo.so”) and add the following line wherever you wish (i.e., at the beginning, the end, or alphabetical):
LoadModule php5_module "c:/php/php5apache2_2.dll"

Be sure that the path within the quotation marks points to your PHP directory and to the correct DLL file.

  • Find the area that lists the “AddType” declarations (i.e., “AddType application/x-compress .Z” and add the following line at the bottom of that list:
AddType application/x-httpd-php .php

PHP Configuration

  • Open up php.ini (the file you dropped into the C:\Windows\ directory). Find the line that looks like this: “;extension=php_mysql.dll” uncomment the line by removing the semicolon.
  • Add “C:\php” to your PATH environment variable.