Archive for the ‘Zend Framework’ Category

How To Count Rows With Zend_Db_Table

Posted on November 18th, 2009 in Web Development, Zend Framework | No Comments »

This is just a quick tip but seems to stump a lot of people, probably because it is not at all clear in the Zend Reference how to do this. So if you want to count the number of rows in a table using SQL you would write something like:

SELECT count(*) FROM myTableName WHERE someColumn='someValue';

But when you are using a Zend_Db_Table it’s a little confusing how to get the “count(*)” part to work because Zend_Db_Table likes to throw errors saying that it can’t be joined with other tables. So, in your Zend_Db_Table class, here is the syntax you can use:

$sql = $this->select()
       ->from($this, 'COUNT(*)')
       ->where('parent_id=?', $this->id);
echo $this->fetchRow($sql)->num;

Zend_Db_Table Not Returning Last Insert Id

Posted on November 3rd, 2008 in PHP, Web Development, Zend Framework | 4 Comments »

I just discovered a significant “gotcha” debugging some code today. Judging from the comments on a variety of blogs and forums I think many of us have had this question. To cut to the chase, if you aren’t getting your last insert id returned when you do a Zend_Db_Table insert, make sure that the array that you are inserting does not have an empty string or a zero set in the primary key field. So, if your primary key column in your database is `id` then this will cause you problems:

//NOTE: $table is an instance of class that extends Zend_Db_Table_Abstract
$data = array('id'=>'', 'color'=>'blue', 'size'=>'large');
$id = $table->insert($data);
echo $id; // --> will print an empty string

If you have to include the name of your primary key column as a key in the array you are tyring to insert, make sure it’s set to null NOT an empty string or zero.

//NOTE: $table is an instance of class that extends Zend_Db_Table_Abstract
$data = array('id'=>null, 'color'=>'blue', 'size'=>'large')'
$id = $table->insert($data);
echo $id; // --> will print the id of the newly inserted row

The reason for this is line 822 in the Zend_Db_Table_Abstract class:

if ($this->_sequence === true && !isset($data[$pkIdentity])) {
  $data[$pkIdentity] = $this->_db->lastInsertId();
}

Notice the isset() condition. If primary key value in the data array you are inserting contains anything other than null then isset() will return true causing the lastInsertId() function to not get called. Hopefully this will clear things up and save us all alot of debugging time!

Zend Framework: Redirect – The Easy Way

Posted on October 28th, 2008 in PHP, Web Development, Zend Framework | 9 Comments »

It is common to need to redirect from one controller action to another or even from one controller to another when coding with the Zend Framework. From my code reviews, I find that many people are using the _redirect() method from Zend_Controller_Action. This function takes a url and an optional array of options. This is a fine choice if you need to redirect to a completely different website but the vast majority of redirect in a web application is to another action within the same application.

The lesser known, and much easier, way to redirect within the Zend Framework is to use the Redirector Zend Controller Action Helper

The syntax is much easier since you don’t have to reconstruct a complete url, you just pass in the action and controller names. In fact, the only required parameter is the name of the action. If only an action name is given then the current controller is assumed to be the target controller. Here is a quick example.

_helper->redirector('target', 'example');
    // NOTE: 'example' is optional since the default target controller
    // is the current controller
  }

  public function targetAction() {
    // Do some things...
  }

}
?>

Zend Framework: How To Disable A View In An Action

Posted on September 17th, 2008 in PHP, Web Development, Zend Framework | 3 Comments »

Sometimes, especially when just testing things out, I don’t want to go to the trouble of having to create view script for my Controller Action and instead I just want to print something to the screen right from my Controller Action function. I guess because it’s sort of hard to find out how to do this in the ZF Documentation this is one of the most common questions I get asked – even from somewhat seasoned developers. The answer is in the Controller documentation and it’s easy to think that you ought to search under the View documentation to figure out how to turn this stuff off. Whatever the case, here’s the trick.

Read the rest of this entry »

Ecommerce with CodeIgniter

Posted on May 15th, 2008 in CodeIgniter, PHP, Web Development, Zend Framework | 4 Comments »

Ironically the Zend Framework is marketed with the phrase “Extreme Simplicity & Productivity”. I have developed a few sites with it now and I find it to be anything but simple and productive. It’s complicated, has a steep learning curve, and (in my opinion) needs a lot more work. I realize that I’m coming from a RoR background and that is a lot for a PHP framework to try to match. Nevertheless, I am quitting all Zend Framework development until more work can be done on the framework. Then, maybe I’ll reconsider.

I have found CodeIgniter and have now built 3 sites with it. It’s simple, easy to use, speeds up development, has great documentation and, best of all, has won me as a fan. My most recent CodeIgniter project is an educational/e-commerce site about Rebounding with the Cellerciser While developing the site and reading the site content, I was convinced of the many reasons to use a Cellerciser I’ve now been using a Cellerciser for about 3 months and I love this thing!

Read the rest of this entry »

How To Sort A Zend_Db_Table_Rowset

Posted on February 14th, 2008 in PHP, Web Development, Zend Framework | 3 Comments »

So you figured out how to define the relationships between your Zend_Db_Tables and you have issued a call to findDependentRowset(). You get your Rowset back but you need to sort the results by one of the columns in the dependent table. How do you do that?

The short answer is, you can’t! Unfortunately, this functionality won’t be available until the 1.5 release of the Zend Framework. But you can write your own utitlity function to sort your Rowset for you.

Read the rest of this entry »

How To Implement Partials In Zend Framework 1.0.3

Posted on February 11th, 2008 in PHP, Web Development, Zend Framework | No Comments »

The pre release of Zend Framework 1.5 has been out for a few days and includes an implementation for partials – among other things. But the GA release is still at least a few weeks off and I’ve got a project that needs to go live very soon. So, I’m using version 1.0.3 of the Zend Framework released on 11/30/2007, and I want to make use of partials in my project. The trick involves three steps.

  1. Create a View Helper
  2. Access your Zend_View object from the View Helper (or instantiate a new one)
  3. Render a view script from within the View Helper

Read the rest of this entry »

How To Implement A Ruby on Rails style before_filter With The PHP Zend Framework

Posted on January 30th, 2008 in PHP, Ruby on Rails, Zend Framework | 2 Comments »

I often use this when implementing a simple login screen for a password protected section of my application. In a Zend Framework application you can implement a preDispatch() function in a Zend_Controller_Action which will run before an action is dispatched. This lets you setup your filter to check to see if the visitor is logged in or not. If the visitor is not logged in, you can redirect them to the login screen of your application.

Setting Up Exceptions For preDispatch

If your login screen is managed by a different controller, the setup described above is fine. If, however, your login screen is managed by an action in the same controller as the protected actions, you will want to allow unauthenticated access to the login screen. To do this, we need to exclude certain actions from the authentication check. Ruby on Rails let’s you define :except => :actionName to allow certain actions to skip the before_filter. With the Zend Framework, we have to implement that functionality on our own… but it’s easy.

What Action Is Being Called?

To set up your preDispatch function to skip checking to see if a user is logged in for certain actions you need to know which action is being called. You do that like this…

$action = $this->_request->getActionName();

Example Code

Now all you have to do is see if the action that is being called is one of the actions that you want to skip. I set up a private function called verify() to check whether or not the visitor is logged in. If the user is not logged in, I forward them to the loginAction() function. Since an unauthenticated user needs to be able to access the login screeen, we tell the preDispatch() function not to verify visitors requesting the login action. My controller ends up looking someting like this.

class AccountController extends Zend_Controller_Action {

  function preDispatch() {
    // Discover what action is being requested
    $action = $this->_request->getActionName();

    // Create a list of actions which allow unauthenticated access
    $exclusions = array("login");
    if(!in_array($action, $exclusions)) {
      $this->verify();
    }
  }

  /**
   * Check to see if the visitor is logged in. If not, send to loginAction
  */
  private function verifty() {
    $auth = Zend_Auth::getInstance();
    if(!$auth->hasIdentity()) {
      $this->_forward("login");
    }
  }

  function loginAction() {
    // Display your login screen
  }

  // Continue the rest of your class...
}

QuietHeadphones.com Goes To Zend Framework

Posted on January 24th, 2008 in PHP, Web Development, Zend Framework | 1 Comment »

A while back I wrote about using Ruby on Rails to develop noise reduction headphones. Tonight, we made the move to the Zend Framework. We did this for a variety of reasons including the fact that we are now hosting our site on a dedicated server with RackSpace. RackSpace is the absolute best hosting company on the planet provided you can afford their rates. RackSpace does not “officially” support Ruby on Rails. This was one of the significant factors in choosing the Zend Framework. Check back soon and I will have a fairly comprehensive comparison of our experience in developing an ecommerce website with the PHP Zend Framework versus our experience building the exact same site with Ruby on Rails.

In the meantime, we have two new products on the website. By popular demand, we now have an amazing set of speakerless noise reduction headphones. We also have a great budget set of noise canceling headphones that are smaller than our premier EX-29 Extreme Isolation Headphones. This makes them great for travel!

Add View Helper Paths For Entire Zend Framework Application

Posted on January 17th, 2008 in PHP, Web Development, Zend Framework | No Comments »

I have been writing several Zend_View_Helpers to aid in the development of my Zend Framework Application. The helpers are very generic and are used in many of my Views throught my applications. So, naturally, I want an easy way to configure my Views to have access to my custom View Helpers. You don’t want to override the init() function in ALL of your controllers to set the View Helper path. Instead, set it in the bootstrap file – your index.php file in the root directory of your website. You do it like this:

$view = new Zend_View();
$view->addHelperPath("DU/View/Helper", "DU_View_Helper");
$viewRenderer = new Zend_Controller_Action_Helper_ViewRenderer();
$viewRenderer->setView($view);
Zend_Controller_Action_HelperBroker::addHelper($viewRenderer);

Put those lines of code in your index.php file somewhere before you call dispatch() on your front controller and all of you view scripts will have access to your own library of View Helpers.

My company’s name is Digital Underware so I have my library set up just like the Zend library in the lib directory of my application. The path to my View Helpers is lib/DU/View/Helper just like the path to the built-in Zend View Helpers is lib/Zend/View/Helper.

If you are interested in seeing a complete example, take a look at this bootstrap file.

Get Adobe Flash playerPlugin by wpburn.com wordpress themes