Posts Tagged ‘PHP’:


PHP Object Generator

As a developer of both Rails and PHP I am lucky enough to see the advantages one has over the other. One of the clear advantages Rails has over PHP is its RAD capabilities. This is largely thanks to ActiveRecord and the fantastic Rails command line tools.

PHP however, does not have these command line tools and while there is an implementation of ActiveRecord for PHP, it is not native to PHP and in my opinion, some how just doesn’t feel right. Others may disagree but that is just my opinion. As a result of this, writing objects in PHP is a labour intensive and lets face it; boring task! Get this set that…. so much time wasted on repeating the same task.

Anyway, last weekend I set about writing an object generator that would some how mirror the abilities of the Rails command line. I ended up with this.

All you have to do is install the object_generator folder into your site. Then, navigate to yoursite.local/object_generator, enter the name of what you want your object to be called and the table that it will represent and click submit. A file will then be created in the object_generator folder which you can copy and paste to your desired location. Each object created will extend my standard Object class which contains the following useful methods:

// Create a new object instance where $id represents the primary key of a table row
$user = new User( $id );
									

// Edit some attributes
$user->setName( $name );
$user->setAge( $age );
									

// Save the object
$user->save();
									

// Represent the object as an array
$user->toArray();
									

// Delete the object
$user->delete();
									

Enjoy and if you have any questions, please feel free to ask! To download the source code, go to my GitHub repo

Database Abstraction

When using MySQL in PHP I often use a simple database abstraction class that I wrote some time ago. This class sits as a layer between the application and database layers. I find that this really shortens the amount of code I have to write. The result is a more organic, succinct script. At this stage the class only has three main abstraction methods:

Database::fetchAll( $sql ); Database::fetchAssoc( $sql ); Database::query( $sql );
									

Example usage would be as follows:

// You'd probably wanna put this in a constructor somewhere or something like that....
Database::conect();

$sql = "SELECT * FROM `users`";
$result = Database::fetchAssoc( $sql );

// Loop through the results and print each user's first name
foreach( $users as $user ){
    print $user['first_name'];
}

// Like connect, you might want to put this is a destructor...
Database::close();
									

You can download the class from my GitHub repo at https://github.com/mikedhart/Database-Abstraction

Tags: , ,

Spl Stack Tutorial

This week I needed to run a series of procedures in a standard first in, last out methodology. I could, of course, have used an array for this, however, I decided to try out a stack.

Spl data structures are often over looked in PHP. However, as PHP advances into a more object orientated environment, I think it is important that we stand up and take note because structures allow us (as web developers) to use traditional programming data structures in our code.

Here’s how we would initiate a stack:

$stack = new SplStack();
									

A stack is essentially an array and has two primary functions:

$stack->push( $mixed );
$stack->pop();
									

Imagine a pile of books on a desk. You can put a book on top of the pile and take a book from the top of the pile and nothing else (without things getting messy). This is essentially how a stack works. The “push” method will put a metaphorical ”book” on top of the pile and the “pop” method will remove whatever is at the top of the pile. Its that simple.

So, what else can we do with SplStack? The SplStack class has three implementations. Iterator, ArrayAccess and Countable. The Iterator implementation is very important as it allows us to iterate over each element stored in the stack. Por ejemplo:

$stack = new SplStack();

$stack->push( 1 );
$stack->push( 2 );
$stack->push( 3 );

foreach( $stack as $s ){
    echo $stack->pop();
}

// This would output: 321
									

ArrayAccess allows us to do exactly that. Here is an example:

$stack = new SplStack();

$stack[] = 1;
$stack[] = 2;
$stack[] = 3;
									

Finally, Countable simply allows us to count how many elements are stored in the stack:

// Using the above $stack instance
echo $stack->count();

// This would output an integer of 3
									

In the coming posts, I will write more about Spl data structures. Next time, I will focus on the class:  SplQueue.

Tags: , ,

Engine Yard Acquire Orchestra

Engine yard’s acquisition of orchestra spells great things for the future of the way we develop web applications.

Engine yard offers a revolutionary way to develop Rails apps in a cloud based environment and the news that we will soon be able to develop PHP apps in this environment is fantastic.

For anyone who has not yet tried Engine Yard, I would seriously recommend it. Every new user gets 500 free hours of development time so there is no excuse not to try it! Here’s the link.

Tags: , ,

Zend Form Validation

Today, I’d like to talk about validating form data with Zend.  Traditionally, validating form data in PHP is quite a cumbersome task, especially when it comes to validating email addresses. We might detect characters such as (\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6}) and then either send the data back to the user to re enter data or use str_replace() to get rid of the unwanted characters.  The beauty of Zend however, means that we can deal with this task with ease. See below:

    /**
     * Validate the new user data
     * 
     * @param array $data
     */
    protected function validate(array $data)
    {
        $emailValidator = new Zend_Validate_EmailAddress();

        if($emailValidator->isValid($data['username']) && $data['password'] == $data['verify_password']){
            return true;
        } else{
            throw new Exception("Please ensure that your passwords match and that you have used a valid email address");
        }
    }
									

This is a simple custom function which I have written to validate a “register user” form. Firstly, we pass in the post data to the function this can be done as follows:

// The Zend way
$data = $this->_request->getPost()

// The traditional way
$data = $_POST;
									

We then create a new instance of the Zend email validator

$emailValidator = new Zend_Validate_EmailAddress();
									

We then run the email address through the validator using a simple if statement and the isValid() method of the validator object.

if($emailValidator->isValid($data['username']) && $data['password'] == $data['verify_password']){
            return true;
        } else{
            throw new Exception("Please ensure that your passwords match and that you have used a valid email address");
        }
									

If all is well, we return true if there is a fault, we throw an Exception. Simple as that.

There are tons of validators for Zend. Some of them are:

  • Zend_Validate_Alpha
  • Zend_Validate_Alnum
  • Zend_Validate_Db_RecordExists
  • Zend_Validate_Iban

For a full list, check out the documentation over at http://framework.zend.com/manual/en/zend.validate.set.html

Tags: , ,
-->
© Mike Hart