Posts Tagged ‘Tutorial’:


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: , ,

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: , ,

Multithreading in Ruby

Today I needed to create a script that would crop a batch of images as a user uploads them. This worked great when only a couple of images were being uploaded however, when the user needed to upload ten images for example, things got a bit clunky.  Coming from a PHP background, I naturally would have resorted to some kind of AJAX request and a “please wait” message.  However, with Ruby, there comes another option, in the form of multi threading.  This would allow me to do each image edit simultaneously and thus giving the user the fastest experience possible.

Anyway, to cut to the chase, here’s how I did it, in a much simplified example:

def my_func(variable)

puts variable

end

puts "All done!!"

threads = []

['a','b','c'].each do |letter|

threads << Thread.new {my_func(letter)}

end

threads.each do |t|

t.join

end
									

So to explain what this actually does:

  • First we simply write a method “my_func” which prints the contents of the variable to the command line.
  • After this we iterate through an array of letters, creating a new thread for each one. This thread will run “my_func”.
  • Finally, “t.join” will halt the progress of the main thread (the main application) until “t” is complete.

So that’s the basics of multithreading in Ruby. For more information on this, I recommend heading over to http://www.tutorialspoint.com/ruby/ruby_multithreading.htm

Stay tuned for more of the same!

-->
© Mike Hart