Posts tagged 'example'

Starting with Zend Framework - part 2

published on October 20, 2008.
Heads-up! You're reading an old post and the information in it is quite probably outdated.

This post is the second part of my introductory text on Zend Framework, Starting with Zend Framework. This time I cover the basics about controllers, actions, view scripts and view helpers. On request routing and the Front Controller I will write one (or more) big post(s), so this part won’t be explained now. I will also skip explaining the models; they deserve their own post :)

If anyone is into writing a guest-post on models, let me know!

The Controllers

The Controllers are the heart of every MVC based application. They control the execution of the application, what to do with the data, what to show the user, what to write to the database, etc. The Controllers that you will write all the time, are called Action Controllers. These Controllers subclass the Zend_Controller_Action abstract class. Every application module must have a default Controller, which will be accessed if no specific Controller is requested. The default name for this default Controller is Index. Examples of the IndexController and FooController:

<?php

// The IndexController class must be placed in the controllers folder
// and saved as IndexController.php
class IndexController extends Zend_Controller_Action
{
    public function init()
    {
    }

    public function indexAction()
    {
    }
}

// The FooController class must be placed in the controllers folder
// and saved as FooController.php
class FooController extends Zend_Controller_Action
{
    public function init()
    {
    }

    public function indexAction()
    {
    }

    public function barAction()
    {
    }

    public function someRandomFunctionDoingSomeFunkyStuff()
    {
    }
}

The Controllers must contain at least the indexAction() function; the others are arbitrary. I always have an init() function, in which I setup the cache object, call up the models, etc. Controller names that are not in the “default” module, must be prefixed with the Title-cased name of the module and an underscore:

<?php

// An example of the IndexController in the
// dummy module
// The file name remains IndexController.php!!!
class Dummy_IndexController extends Zend_Controller_Action
{
}

// An example of the FooController in the
// dummy module
// The file name remains FooController.php!!!
class Dummy_FooController extends Zend_Controller_Action
{
}

The actions

Actions are methods of the Controller class. Use them to do some specific task: show users, list news, insert to database (the actual INSERT SQL statement should be in the model), etc. As stated before, every Controller must have an index action — this one is called if no specific action is requested. By default the view object is instantiated, so if you don’t turn it off, you must create a view script with the same name as the action (without the “Action” word) in the views/scripts/foo/ folder.

Assigning variables to the view scripts is simple:

public function indexAction()
{
    $this->view->someVariable = "some value...";
}

The view scripts

View scripts are, well, for viewing. This is the only place where you should have statements like echo and print. The default templating engine is PHP itself, but it’s possible to change it to something like Smarty. I leave PHP; it has everything for templating, so why would I change it? The default file extension for view scripts is “phtml” — but as with everything, this can also be changed :)

Getting variables that are assigned from the action:

// Output: some value...
<?= this->someVariable ?>

The view helpers

The view helpers are simple classes that help in view scripts with things like formatting dates, creating links, etc. Here’s an example view helper that I use to show dates in “Serbian” format:

File name: views/helpers/SrDateFormat.php
<?php
/**
* View helper for returning dates in Serbian format
* dd.mm.yyyy.
*
*/
class Zend_View_Helper_SrDateFormat
{
    public function srDateFormat($dateToFormat)
    {
        return date('d.m.Y.', strtotime($dateToFormat));
    }
}

Usage is quite simple:

// somewhere in some view script...
<?= $this->srDateFormat($someDateToShow); ?>

Bringing it all together

Just for an overview, here is an example of a Foo Controller in the Dummy module with index and bar actions and their view scripts.

<?php
// File name: application/dummy/controllers/FooController.php
class Dummy_FooController extends Zend_Controller_Action
{
    public function indexAction()
    {
        $this->view->sayHello = "Hi there!";
    }

    public function barAction()
    {
        $this->view->sayHelloAgain = "Hi here :)";
    }
}

And the view scripts:

<!-- File name: application/dummy/views/scripts/foo/index.phtml -->
<h1>Saying hello</h1>
<?= $this->sayHello ?>

<!-- File name: application/dummy/views/scripts/foo/bar.phtml -->
<h1>Saying hello again</h1>
<?= $this->sayHelloAgain ?>

So if you direct your browser to “http://example.com/dummy/foo/&#148; or to “http://example.com/dummy/foo/bar&#148; you should get the “Saying hello” or the “Saying hello again” page…

This would be my introductory text to Zend Framework. Hope it’s not confusing and is easy to follow. I just want to help newcomers to ZF help settling in easily :) For a tutorial application with ZF, I recommend Rob Allen’s Zend Framework tutorial.

In the coming days/weeks I’ll write a detailed post about the Front Controller, so if you wish, grab the feed or subscribe by E-mail to stay tuned.

Cheers!

Wordpress paging navigation

published on October 06, 2008.
Heads-up! You're reading an old post and the information in it is quite probably outdated.

As I’m not a big fan of Wordpress plug—ins, and I wanted to use a normal page navigation, not just the default “Previous posts” and “Next posts”, I decided to play around a bit and create my own paging navigation, or pagination.

Preparation

First, I wrote on a piece of paper which links I need: first page, last page, next page, previous page and the links with the page numbers. Next, I needed to see what functions are already in Wordpress, to reuse as much as I can. After a little searching, I found that the functions for the default navigation are located in the link-template.php file, under the wp-includes folder. There are the functions for the next and previous pages, and the function that creates the URL. Furthermore, I wanted a sliding pagination (like Yahoo has on it’s search page), ‘cause it’s easy to use and looks cool.

The function

So, let’s take a look at the code. I called the function simply get_pagination; it’s quite self—describing. I put it in the link-template.php file, that way, all functions for navigation are in one place.

<?php
/**
* A pagination function
* @param integer $range: The range of the slider, works best with even numbers
* Used WP functions:
* get_pagenum_link($i) - creates the link, e.g. http://site.com/page/4
* previous_posts_link(' &laquo; '); - returns the Previous page link
* next_posts_link(' &raquo; '); - returns the Next page link
*/
function get_pagination($range = 4){
  // $paged - number of the current page
  global $paged, $wp_query;
  // How much pages do we have?
  if ( !$max_page ) {
    $max_page = $wp_query->max_num_pages;
  }
  // We need the pagination only if there are more than 1 page
  if($max_page > 1){
    if(!$paged){
      $paged = 1;
    }
    // On the first page, don't put the First page link
    if($paged != 1){
      echo "<a href=" . get_pagenum_link(1) . "> First </a>";
    }
    // To the previous page
    previous_posts_link(' &laquo; ');
    // We need the sliding effect only if there are more pages than is the sliding range
    if($max_page > $range){
      // When closer to the beginning
      if($paged < $range){
        for($i = 1; $i <= ($range + 1); $i++){
          echo "<a href='" . get_pagenum_link($i) ."'";
          if($i==$paged) echo "class='current'";
          echo ">$i</a>";
        }
      }
      // When closer to the end
      elseif($paged >= ($max_page - ceil(($range/2)))){
        for($i = $max_page - $range; $i <= $max_page; $i++){
          echo "<a href='" . get_pagenum_link($i) ."'";
          if($i==$paged) echo "class='current'";
          echo ">$i</a>";
        }
      }
      // Somewhere in the middle
      elseif($paged >= $range && $paged < ($max_page - ceil(($range/2)))){
        for($i = ($paged - ceil($range/2)); $i <= ($paged + ceil(($range/2))); $i++){
          echo "<a href='" . get_pagenum_link($i) ."'";
          if($i==$paged) echo "class='current'";
          echo ">$i</a>";
        }
      }
    }
    // Less pages than the range, no sliding effect needed
    else{
      for($i = 1; $i <= $max_page; $i++){
        echo "<a href='" . get_pagenum_link($i) ."'";
        if($i==$paged) echo "class='current'";
        echo ">$i</a>";
      }
    }
    // Next page
    next_posts_link(' &raquo; ');
    // On the last page, don't put the Last page link
    if($paged != $max_page){
      echo " <a href=" . get_pagenum_link($max_page) . "> Last </a>";
    }
  }
}

The “range” is the range of the sliding effect, i.e. how many numbers are shown besides the current number: if the range is 4, and the current page is 5, then the numbers 3, 4, 5, 6 and 7 are visible.

Usage

It’s quite simple to use it: where the pagination is needed, just call the get_pagination() function, and it will show up. Add some CSS style to it, and your good to go.

Hope someone will find this useful :)

Regular expressions with PHP

published on September 22, 2008.
Heads-up! You're reading an old post and the information in it is quite probably outdated.

I just want to write some real examples. These regexps are (and always will be, ‘cause I plan to write several posts on this topic) for the PHP’s PCRE library. Here’s a good PHP PCRE cheat sheet, it’s an excellent resource for regexps. If you know nothing about regexps, first read this Wiki page.

Regexps for anchor tags

A common case is when you have a source of some web page and you want to parse out all the links from it.
An anchor tag goes something like this:

<a href="http://example.com/" title="Some website">Website</a>

Also it can have more attributes, like class, target etc. Knowing how it’s built up, we can start writing a pattern, depending on what we want.
Here are some examples, some explanations are in the comments:

<?php
// Regexp examples for <a> tags

/**
* Different combinations...
* $matches_comb[0] contains the whole <a> tag
* $matches_comb[1] contains what's inside the "href" attribute
* $matches_comb[2] contains what's after <a> and before </a>
* with the "s" modifier mathces <a> tags that are broken in several lines,
* ie. matches <a> tags with newlines
* without the "s" modifier, matches only <a> tags without a newline
*/
preg_match_all(
    '#<a\s.*href=["\'](.*)["\'].*>(.*)</a>#isxU',
    $string,
    $matches_comb
);

/**
* Match only what's inside the href attributes...
*/
preg_match_all(
    '#<a\s.*href=["\'](.*)["\'].*>.*</a>#isxU',
    $string,
    $matches_href
);

/**
* Match only what's inside the href attirbutes,
* only when it starts with http:// and includes http://
* $mathces_href_http[0] contains some trash also, nevermind,
* $mathces_href_http[1] contains exactly what we need
*/
preg_match_all(
    '#<a\s.*href=["\'](http://.*)["\'].*>.*</a>#isxU',
    $string,
    $matches_href_http
);

/**
* Match all Email addresses - mailto:
*/
preg_match_all(
    '#"mailto:(.*)"#',
    $string,
    $matches_emails
);

?>

Play around with these patterns, see what’s for what, experiment, that’s the best way to learn regexps.

Do you have some more regexps for links? Some better ones than these here?

Happy hacking!

Tags: example, pcre, php, regex, regexp.
Categories: Development, Programming.
Robert Basic

Robert Basic

Software engineer, consultant, open source contributor.

Let's work together!

If you require outsourcing or consulting help on your projects, I'm available!

Robert Basic © 2008 — 2019
Get the feed