Author Archive for Mark Quezada



17
Feb

Pake Task Locations and File Naming Conventions

I was writing a custom Pake task for a project and was completely stumped as to why the task wouldn’t show up from the command line. Since I only usually write pake tasks for plugins, I was completely confused as to why a file named tasks.php in myproject/data/tasks wouldn’t register its tasks. It turns out that symfony has very specific file naming conventions for Pake tasks depending on where you’re writing them.

Symfony tasks located in:

sf_symfony_data_dir/tasks (the symfony library’s tasks) must have an sfPake*.php naming scheme

sf_data_dir/tasks (your project’s tasks) must have a myPake*.php naming scheme

… and of course plugin tasks located in sf_root_dir/plugins/*/data/tasks can use *.php (which is probably why I’ve never run into this little conundrum before.

You can check which tasks are registered in your project by running:

symfony -T

… at the command line.

12
Feb

sfLucene Quick Tip: Displaying Categories In Model Results

If any of you are using the great sfLucene Plugin, here’s a quick tip on making your search results a bit more intuitive.

This really only applies to model results (not action results) as there’s an option to add a category to each model. Here’s an example search.yml file that would go in your project’s config folder:

MyIndex:
  models:
    Podcast:
      fields:
        id: unindexed
        title:
          type: text
        description:
          type: text
      title: title
      description: description
      validator: isPublished
      categories: [Podcast]

You can see that I’ve added the category “Podcast” to the model’s definition. Now, you can override the plugin’s default display for model results by creating a module in your project named “sfLucene” and overriding the default _modelResult.php partial (in the sfLucene/templates directory) with something like this:

<?php echo link_to($result->getsfl_category() .' &raquo; '. highlight_keywords($result->getInternalTitle(), $query, sfConfig::get('app_lucene_result_highlighter', '<strong class="highlight">%s</strong>')), add_highlight_qs($result->getInternalUri(), $query)) ?> (<?php echo $result->getScore() ?>%)
<p><?php echo highlight_result_text($result->getInternalDescription(), $query, sfConfig::get('app_lucene_result_size', 200), sfConfig::get('app_lucene_result_highlighter', '<strong class="highlight">%s</strong>')) ?></p>

The only thing we’re really changing from the default template is that we’re adding this:

$result->getsfl_category() .' &raquo; '.

…to the beginning of the call to the link_to() helper. The category is stored automatically by sfLucene in this field in the lucene document, so we have access to it in the template. This new partial effectively inserts the category in front of the “title” field (along with a “»” for separation) while building the link, which produces something like this:

Podcast » My Great Podcast Title

As you can see, if you have several model definitions this comes in handy while looking at a list of results since you’d get a nice listing that shows which category each link belongs to:

Podcast » My Great Podcast Title

Blog » This Is Some Article

Podcast » Another Awesome Podcast

… instead of just a bunch of titles in a list.

29
Jan

sfZendPlugin Alternative to Installing the Zend Framework

I often use the Zend Framework from within my Symfony applications and until recently, I’ve been using the sfZendPlugin to import and autoload the library. You’ll notice that this plugin has recently been axed leaving some people confused as to how to use the library in their projects.

Adding the Library

First, you’ll need to add the Zend Framework library. Since I like to link libraries via subversion, I’ll link the Zend Framework to my project’s lib/vendor directory. Open up a terminal to your symfony project’s root directory and type this:

 svn propedit svn:externals lib/vendor/

Note: You may have to create the vendor directory (and use svn add to add it to your repository) if you don’t already have it.

This will bring up a text editor where you can add a link to an external library via subversion. Type this in:

Zend http://framework.zend.com/svn/framework/tag/release-1.5.0PR/library/Zend

… and save and close the file. This will link lib/vendor/Zend to the 1.5.0 PR release of the Zend Framework. You can, of course, use another version if you prefer. Of course, you don’t have to link this via subversion. You can simply download and copy the Zend Framework into this folder for the same effect, but using subversion is my preferred method.

Linking the Library to Symfony

All you need to do now is activate symfony’s autoloading of the library files. Open up your application’s setting.yml file (mine is at apps/frontend/config/settings.yml) and add the appropriate settings. It should look something like this:

all:
  .settings:
    zend_lib_dir: %SF_ROOT_DIR%/lib/vendor
    autoloading_functions:
     - [sfZendFrameworkBridge, autoload]

Make sure to clear your symfony cache by using:

./symfony cc

That’s it! You should be able to use any of the Zend Framework classes from within symfony without using a require statement.

Edit: As per Gerald’s comment below, the zend_lib_dir path was listed as “zend_lib_dir: %SF_ROOT_DIR%/lib/vendor/Zend” but should not included the “Zend” folder name at the end as sfZendFrameworkBridge.class.php actually adds this automatically.

19
Jan

Quick Tip: Symfony and the iPhone WebClip Bookmark Icon

According to the Apple docs, you need to create a 57x57 PNG, name it “apple-touch-icon.png” and upload it to the root of your web directory in order for the iPhone to find and use your icon.

What I found more useful though, was that this can be overridden using a link attribute, similar to the way favicons are handled. This allows us to use symfony’s standard “images” directory to house the icon. So, the head of our layout.php could be updated with the addition of:

<link rel="apple-touch-icon" href="<?php echo image_path('apple-touch-icon') ?>" />

… which would make it look something like this:

webclip example

Note: as this is a post on symfony, I’m using symfony’s built-in image_path helper, but this can be simply href="/images/apple-touch-icon.png" if you’re not into that.

Taking it a Step Further

The way the real power of symfony gets leveraged is when you want to have different icons for different sections of your site. Let’s say you wanted to have a different touch icon related to every different module in your symfony project. Symfony makes this really simple to do. Replace the existing link tag we made earlier with something like this:

<?php if (file_exists(sfConfig::get('sf_web_dir').'/images/webclip_icons/'.$sf_context->getModuleName().'.png')): ?>
    <link rel="apple-touch-icon" href="<?php echo image_path('webclip_icons/'.$sf_context->getModuleName()) ?>" />
<?php else: ?>
    <link rel="apple-touch-icon" href="<?php echo image_path('webclip_icons/apple-touch-icon') ?>" />
<?php endif ?>

Basically, this code just checks to see if there’s a Web Clip icon with the same name as the current module in /images/webclip_icons and if it finds it, it links to that one instead of the default one.

Of course, this is just an example of how powerful and easy this is. This idea could be extended in many different ways.

More Info

You can read more about iPhone development at Apple’s iPhone Dev Center. One of the more useful pages on that site is the one on Designing Content.

Also, as noted elsewhere, you seem to get a crisper icon if you use a 60x60 image at 72 DPI.

05
Jan

Setting up a Symfony project on Media Temple’s Grid Service, Part 2

In part one of this series, we looked at setting up a basic Subversion repository to house our new Symfony project on Media Temple’s Grid-Service. This article will take that a step further by explaining how to set up your OS X box for local development using said repository. Although this article will start from where we left off last time, there’s really nothing specific to Media Temple about these steps and these same basic principles can be used with any other host.

I think a lot of people don’t really understand the benefits of local development. For those who are unfamiliar, “local development” means simply that your machine acts as both client and server. This means that instead of, say downloading a file from your server, editing it, and uploading it to see changes, you simply edit and save the file right on your machine and see changes reflected instantly. There’s really no magic here, it’s just that we do the hard work up-front to have an apache server running on our local machine so that simply saving a file is saving to the server.

Requirements

Installing and configuring Apache, MySQL and PHP5 are out of the scope of this article, but we’ll be working on the assumption that these are all installed and working. Mac OS X has long shipped with an Apache server built-in, and version 10.5, Leopard, ships with Apache2 and PHP5 pre-installed. The shipping version of those two packages may be all you need, but I’ve been using Marc Liyanage’s PHP5 package with a custom Apache2 install for various reasons (namely, Apple’s PHP5 version is missing some critical libraries like mcrypt and GD). At the time of this writing there is currently no supported version of his PHP package for use with Leopard, but there are various threads on his forum about getting it working. You can also use something like MAMP (along with these setup instructions for Leopard).

Setting Up the Development Environment

We left off on the previous article with a working copy checked out of our Subversion repository into the ~/Sites/ folder. All we need to do now is map the web directory in our Symfony project to an Apache Virtual host so we can serve it up locally.

Find your apache config file and edit it appropriately. I like to have separate config files for each site that I’m working on, so I’ve edited my main config file located at /usr/local/apache2/conf/httpd.conf and added the following line at the end of that file:

# Include custom configurations for symfony
Include conf/sites/*

This basically tells the Apache server to look in conf/sites/ for any extra configuration files and load them as well. I’ve then added a config file for each site that I’m working on. For example, in conf/sites/project1.conf we’ll add this:

<VirtualHost project1.dev:80> 
    ServerName project1.dev
    <Directory />
        AllowOverride All
        Allow from All
    </Directory>

    DocumentRoot /Users/mark/Sites/project1/web

    ErrorLog logs/project1.dev-error_log
</VirtualHost>

… which will allow us to access our symfony project. Be sure to substitute your own username in the DocumentRoot directive and restart the apache server so that the changes take effect.

We’ll also have to edit our hosts file so that “project1.dev” is considered a valid hostname for our machine. In /etc/hosts/ add this line:

127.0.0.1 project1.dev

It should be noted that I like to use the “.dev” domain for my dev environment, but this is simply my own convention. I’ve heard of other symfony users using something like “.sf” instead which would work just as well.

You should now be able to pull up http://project1.dev/ from a browser and see the default symfony project page.

Some Added Sugar

At this point we pretty much have a working local copy of our symfony project. It’s running as a subversion working copy which allows us to track and check-in changes, which is great. We are also able to test our site using any browser on our machine be it Safari, Firefox, Camino or anything else that’s native to Mac OS X. The one thing we can’t do is test our site locally using a PC version of Internet Explorer, which still accounts for about 75% of browsers.

One great thing about Apple’s recent switch to Intel processors is the ability to run Windows through virtualization right from within OS X. If you’ve got VMware’s Fusion installed, we can update our setup a bit so that we can check our site from Windows, without needing another physical box.

First, boot up your Windows XP virtual machine and open a command prompt by choosing “Run…” from the Start Menu and typing in “cmd”:

Windows Start Menu

Windows Run Command

Once you’ve got the prompt, type:

ipconfig /all

This will list all of your network adapters. What we’re looking for is the “Default Gateway” entry under the Ethernet adapter heading.

Windows Default Gateway

Copy down that IP address. Now, open your hosts file which is probably located at C:/WINDOWS/system32/drivers/etc/hosts in your favorite editor (notepad works fine).

Windows Hosts File

This is essentially the same file we just edited on OS X, but there will be one major difference. We’re going to put the IP of our host machine as the mapping IP for our development domain like so:

192.168.171.2   project1.dev

Now, you should be able to open a browser on your Windows Virtual Machine and see the same symfony project that we just set up on OS X. The only downside I’ve seen with this is if your Gateway IP changes on the Windows box. You’ll have to update the Windows hosts file to reflect the new IP. I’m sure there’s probably an automated way to do that, but my IP seems to be pretty consistent unless I actually shut-down the Virtual Machine instead of just suspending it.

Next Steps

At this point you can also install and configure your database software. MySQL makes it easy with their OS X installer which even comes with a startup script. As of this writing, there is still no Leopard specific version, but there are instructions elsewhere on loading MySQL or migrating from Tiger.

Once it’s installed, you can add a database that will be for local development and then update your symfony config/databases.yml file with the information:

dev:
  propel:
    class:          sfPropelDatabase
    param:
      dsn:          mysql://user:pass@localhost/project1_db

prod:
  propel:
    class:          sfPropelDatabase
    param:
      dsn:          mysql://user:pass@internal-db.sXXXXX.gridserver.com/project1_db

…where sXXXXX is substituted with your Grid Server account number. You’ll notice that we’ve set up our dev and prod environments to use different databases. The dev environment uses the DSN for the local database you just installed while the prod environment uses a Media Temple specific DSN. This means that when developing locally, we’ll always be calling the dev environment from our browser so that we’re loading the correct database:

http://project1.dev/frontend_dev.php

Conclusion

I hope this provides some insight as to why local web development on an OS X box works so well. You get to edit and save files without the delay of saving to a server and you get to have an all-in-one testing machine that you can use to test sites in different browsers and on different platforms.

15
Dec

Setting up a Symfony project on Media Temple’s Grid Service, Part 1

Media Temple’s Grid-Service is a great, low-cost solution for developing and deploying Symfony applications. This article will walk you through setting up a Grid-Server Subversion repository for use with a Symfony project. The main point here is being able to create and use a symfony project hosted on a Grid Server without having to have symfony pre-installed at all locally.

Setting Up Subversion

Symfony is designed to be used with version management software like Subversion. If you’ve never used versioning software, you should read about the benefits right from the Subversion book itself, but in general, it tends to make life easier for developing and maintaining large code bases as it tracks revisions between files and authors. Subversion is already installed in the Grid-Service environment, so all we have to do is set up a new repository. Media Temple has a knowledge base article describing the basic steps, but we’ll be tailoring things a bit to Symfony.

Be sure that you’ve enabled SSH access on your account. Personally, I like creating the repository using the serveradmin user, and then I’ll make commits using a local user on whichever domain I’ll be using. Let’s get started.

Once you’ve logged in via SSH as serveradmin, move into the data directory. This is where we’ll be creating the repository:

cd data

Then, create the base repository like so (substituting your own repository name for mirthlab):

svnadmin create --fs-type fsfs mirthlab

I tend to use separate repositories for each domain. This allows me to use a structure of the form:

mirthlab/
    project1/
        trunk/
        tags/
        branches/
    project2/
        trunk/
        tags/
        branches/
some_other_domain/
    project3/
        trunk/
        tags/
        branches/

… so I can effectively have as many projects related to each domain in version control as I need.

Now that we’ve created the repository, let’s create the base folder for the Symfony project. While still in the data directory, we’ll create a few new folders:

mkdir project1
mkdir project1/trunk
mkdir project1/tags
mkdir project1/branches

… where project1 is the name of your symfony project. This might all look familiar if you’re read through the Subversion documentation, but we’re going to add a couple of folders:

mkdir project1/trunk/lib
mkdir project1/trunk/lib/vendor

It’ll become clear in a moment why we’re doing this, but the short of it is that we’re going to link the Symfony libraries directly to the project itself using the lib/vendor folder. Once you’re done, commit the contents of your project folder to the repo like so:

svn import project1 file:///home/<site_number>/data/mirthlab/project1 --message "Creating initial repo."

Be sure to change <site_number>, mirthlab and project1 appropriately, so that they match your setup. Please note that this assumes you’re starting with a fresh Symfony project. If there’s an existing project you have that you want to import into the repository, these steps would vary slightly since you wouldn’t have to set up a lib folder.

The folder structure was imported into the repository, so you can safely delete the project folder skeleton we made from the data folder:

rm -rf project1

Set Up Additional SVN Users

This step is optional, but would be helpful if you’re going to allow multiple users to work on this repo. There’s also a Media Temple KB article for this if you’re curious. Log in to your Media Temple Account Center for your domain. Click on the “Email Users” button and add some local users.

Email Users Button

I created a user “mark” for my domain. Also, be sure to check the “Enable SSH access?” checkbox:

image here

Now, in order to allow other users to use the new repo, we have to give group access to the directory. From within the data directory run this command as serveradmin:

chmod -R g+w mirthlab

Again, being sure to substitute your own repository name for mirthlab.

Setting Up Symfony

Now that you have your base folder structure, it’s time to get the Symfony project initialized. Connect to your Subversion repository and download the trunk of our project by running the following commands locally. I’m on a Mac OS X box, so I’ll use the terminal to do a checkout of my project to the ~/Sites folder:

cd ~/Sites
svn checkout svn+ssh://your_user%your_domain.com@your_domain.com/home/<site_number>/data/mirthlab/project1/trunk project1

Note: svn checkout svn+ssh... should all be on one line. This creates a project1 folder in my Sites folder, which is just what I want. Now let’s get our Symfony project structure set up by linking the Symfony libraries to our lib/vendor folder with a subversion externals link.

cd project1
svn propedit svn:externals lib/vendor/

This should bring up your favorite text editor. Simply paste this line into the file, save and close it:

symfony http://svn.symfony-project.com/branches/1.0

This effectively links lib/vendor/symfony to the stable 1.0 branch of Symfony. Only security and bug fixes go into this branch, so there’s no need to worry about it breaking your app when running an svn up. Now, commit your changes back to the repository:

svn commit --message "Linking Symfony libraries to lib/vendor"

And when that’s done, update the local working copy to get the libraries:

svn up

Since we now have a local copy of symfony, we can use the symfony binary to execute pake tasks. Let’s flesh out our project by creating the initial structure using the init-project task.

lib/vendor/symfony/data/bin/symfony init-project project1

… where project1 is the name of our project. This doesn’t necessarily have to match the name of your repository project, but that’s usually what I use. This project name is used to set up defaults in files like propel.ini and properties.ini.

Also, be sure to change the path for the symfony libraries in config/config.php:

$sf_symfony_lib_dir  = dirname(__FILE__).'/../lib/vendor/symfony/lib';
$sf_symfony_data_dir = dirname(__FILE__).'/../lib/vendor/symfony/data';

… this just sets them up to use a relative path, instead of an absolute one (which we’ll need when we push this code to the production server).

We can now add the rest of the project to source control:

svn add *
svn commit --message "Added initial symfony project structure."

Subversion might complain that the lib folder is already under version control, but that’s ok.

Next Steps

Additional general info on Symfony and Subversion can be gleaned from Dave Dash’s excellent article: Tips for Symfony and Subversion. Read and follow the directions in that article to complete your setup by ignoring files in cache and log as well as other auto-generated files like the model files Propel generates.

Conclusion

With this setup, we now have a Symfony project under source control on a Media Temple Grid-Service account. We also now have symfony installed locally and which we can use by calling simply ./symfony from within our project directory. In the next article, we’ll take a look at getting our local development environment set up for editing on a Mac OS X box.

11
Dec

Custom Propel Criteria Tips

Here’s a quick Propel tip. While working on a site recently, I had to figure out a way to randomly pull some records from a database using Propel from within a Symfony application. This is a bit of a hack as it will only work if you’re using MySQL, but it’s an elegant way (considering the alternatives) to get some random results. I assume you can use this method with another database. You’d just have to figure out what functions to call instead of the MySQL specific ones like RAND() and DAYOFWEEK().

From within an action, you can do something like this:

$c = new Criteria();
$c->addAscendingOrderByColumn('RAND()');
$c->setLimit(20);
$this->photos = PhotoPeer::doSelect($c);

… which will get you a set of 20 random photo objects.

Something a bit more interesting is using a custom criteria. This basically lets you use any MySQL specific function from within propel without resorting to building a query completely from scratch. Take this example:

$c->add(PodcastPeer::DATE, 'DAYOFWEEK('.PodcastPeer::DATE.')='.$this->filters['day_of_week'], Criteria::CUSTOM);

Basically, I wanted to be able to use a symfony-type filter (just like the ones that are generated automatically by the propel admin generators) to filter podcasts by certain days of the week. So someone could, for example, choose only to listen to those podcasts that were released on Wednesdays. This snippet of code basically allows me to run this sql query:

SELECT * FROM podcast WHERE DAYOFWEEK(podcast.DATE)=1

… where 1 = Sunday, 2 = Monday, etc.

06
Dec

Making a Custom Apache Install Start at Boot on Mac OS X

A Bit Of Background

I do all of my web-development on a Mac OS X machine (a MacBook Pro, to be exact) using a local install of Apache, PHP and MySQL. I’m using a custom built Apache 2 install and configuration (for various reasons) so the default Web Sharing control panel does not control the starting and stopping of my webserver. In general, my setup works really well and has led to a really integrated workflow that I can use and develop with even while offline. One thing that had always frustrated me about my custom setup though, is that after a restart, apache had to be manually started before I could get back to work. This is one of those little things that can be annoying, but not really annoying enough to do anything about. Well, I finally decided to fix it.

Mac OS X has a system startup program called launchd which allows us to start the apache webserver automatically on each system boot. You can read more about launchd at the official apple page.

Making Our Own launchd File

To create the launchd plist file, I used Lingon which is an open source graphical front-end for creating these types of files (version 2.0.2 as of this writing). You can use this article as a reference for creating your own, or simply download the apache2 launchd plist file, unzip it, and place the file into /Library/LaunchDaemons/. This file assumes that you have apache2 installed in /usr/local/apache2/.

Once Lingon is launched, you’ll be presented with a window that’ll show you an overview of all of your currently installed launchd files. Click the “new” button to create a new file. You’ll want a Daemon file since apache needs to run at startup and as root:

Screenshot of step 1

Once you’ve got a new file ready for editing, fill out the “Name” field. I’ll be using “com.mirthlab.launchd.apache2”:

Screenshot of step 2

Next, fill out the “What” field. This will be the command we want to run at startup and I’ll be using “/usr/local/apache2/bin/apachectl start” but this may differ if you have Apache installed in a different location:

Screenshot of step 3

And finally, fill out the “When” field. For Apache, I checked the box that says “Run it when it is loaded by the system (at startup or login)”:

Screenshot of step 4

Wrapping It All Up

Click “Save” and enter your password when prompted. This is a root level launchd daemon which is why Lingon needs your password.

Restart and you should have Apache ready to go!

NOTE: If you simply downloaded the plist file, you’ll probably have to change this file’s ownership as files in /Library/LaunchDaemons/ must be owned by root.

To change the file’s owner to root, in the terminal, type:

sudo chown root:wheel /Library/LaunchDaemons/com.mirthlab.launchd.apache2.plist

… all on one line.

You can also see this macosxhints.com hint for a tip on using the Sharing Control Panel to start and stop your custom Apache install.

05
Dec

Welcome to the New MirthLab

Well, here we go. It’s about time, too. This blog has been a long time coming and I hope to make it a useful resource for all things PHP, Symfony, JavaScript, CSS, Mac, Unix and the like. Most likely it’ll be more of an online reference than anything (documenting things I come across while hacking away on some web-development project) so I hope you find these posts to be a useful resource.