Framework of Choice: CodeIgniter

As a developer, I am always looking for ways to increase the quality of my work and the speed at which I complete a project. One of the ways I do this is by utilizing a framework. The framework I choose is CodeIgniter.

What is CodeIgniter?

“CodeIgniter is an Application Development Framework – a toolkit – for people who build web sites using PHP. Its goal is to enable you to develop projects much faster than you could if you were writing code from scratch, by providing a rich set of libraries for commonly needed tasks, as well as a simple interface and logical structure to access these libraries. CodeIgniter lets you creatively focus on your project by minimizing the amount of code needed for a given task.” (http://codeigniter.com)

There is a key word in the definition and that is toolkit. I see and read a lot about beginning PHP developers jumping right into using a framework, such as CodeIgniter. I believe if you want to learn PHP you gotta LEARN PHP! To fully understand the concept of Model-View-Controller (MVC) and the usage of CodeIgniter you should have an understanding of PHP and how it’s used, how to utilize it, etc. It’s also important you have a basic understanding of Object-Oriented concepts.

Why CodeIgniter?

I chose CodeIgniter as my framework of choice primarily because of the swift learning curve. Learning to utilize all of CodeIgniter’s libraries took very little time and practice. The documentation is straightforward, easy to understand and very descriptive in explaining the usage of each library. Each library in CodeIgniter does a good job of handling the task it has been given. For example, the Form Validation library handles everything that has to do with creating a web form, validating a web form and re-populating data back into the form. I have spent hours in the past creating web forms, validating on both client and server side, displaying errors if any and re-populating the form. The time it takes to create a form has been cut in half (if not more) by using CodeIgniter.

CodeIgniter has also helped me find bottlenecks in my code through the use of the Profiler Library. What the profiler does is show the developer (through the browser) how much memory the application is using, what is being loaded, any data that has been posted as well as any MySQL queries that have run and the time it took to execute the query.

These are just a couple of the libraries included with CodeIgniter that help you develop your application quickly. You are not limited to only these libraries either. CodeIgniter allows you to create your own libraries and load them just like any other library. You even have the ability to extend it’s own libraries or override them completely.

I am not writing this to say CodeIgniter is the best PHP framework out there. Every developer writes code in a unique way and/or uses a different set of tools and processes to complete a project. What I am saying is, if you are a Web Developer, you should have a set of tools you use. If not, take some time to create a library for yourself or try out the variety of frameworks out there. Whatever you decide, you need to master it and your process to become the best you can be.

WordPress ‘Fetch Feed’ Plugin

‘Fetch Feed’ is a RSS retrieval and caching plugin for WordPress. You can use it to parse any RSS feed for displaying on your site. The beauty of this plugin is that you are not limited to how you display your feed. All you need to know is a basic understanding of PHP foreach loops and array/object structure.

Installation

  1. Download the file and unzip it. Upload the ‘fetch-feed’ folder to your ~/wp-content/plugins/ directory
  2. Make sure the ~/wp-content/plugins/fetch-feed/cache/ directory is writeable
  3. Activate the plugin through the ‘Plugins’ admin menu in WordPress

Usage

To begin using the function we need to pass the url to the RSS feed we would like to work with and save the result in a variable. I will be using $xml. We will also specify in the second parameter, the amount in minutes we would like the feed cached for:

// Retrieve RSS from http://jrtashjian.com and cache for 60 minutes
$xml = fetch_feed( "http://jrtashjian.com/feed/", 60 );

After the function retrieves the RSS you can loop through the object using a foreach loop, like so:

<h2><?php echo $xml->channel->title; ?></h2>
<ul>
    <?php foreach ( $xml->channel->item as $item ) : ?>
        <li><a href="<?php echo $item->link; ?>"><?php echo $item->title; ?></a></li>
    <?php endforeach; ?>
</ul>

Limit Words in a String

While developing websites, I’ve frequently run into clients who would like a news system integrated on their site. A news system consists of a list of articles, usually a summary at first, and when an article has been selected, the full article is displayed. So, how do you extract the summary from the content without duplicating content?

If you wanted to do this effect quickly, you could just use the function substr(). However, the substr() function only limits the number of characters being displayed. The returned result would be an excerpt of text that may or may not have the ending word cut-off.

The purpose behind this function is to limit the number of words displayed in such a way that the ending word is not cut-off. Personally, I think this small change makes the site look a little nicer.

function limit_words( $string, $word_limit ) {
    $words = explode( " ", $string );
    return implode( " ", array_splice( $words, 0, $word_limit ) );
}

To use this function, pass the text you would like to extract the excerpt from, as $string. Then, set the number of words you would like to display as $word_limit. The function will return the excerpt as a string.

The function separates the string where it finds a space, therefore separating each word using the explode() function. Each word is put into an array called $words. We then cut out the excerpt using the number of words we would like to display ($word_limit) starting from the beginning using the array_splice() function. With the excerpt extracted from the full text, we then recreate the string by adding spaces after each key (word) in the array using the implode() function.

# Example Usage
$content = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
echo limit_words( $content, 20 );

The above example would output this result:

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut

Simple function, Nice results. Enjoy!

Recursive Delete with FTP

I was recently creating an administration application for a client. The app involved working with files and directories as well as uploading and deleting files or directories. While I was developing, I ran into an issue that required a special function: recursive delete.

A recursive function is a function that has the ability to call itself (recursion). I ran into this problem while trying to delete a directory containing files and/or other directories. I was using FTP at the time so, the function will be written as such. It can be easily ported to using filesystem functions by following the same logic/flow.

Anyway, the use of ftp_rmdir() was not enough. Using it to delete a directory containing files or folders only throws an error stating that the folder you are trying to delete contains other files. It was a little disappointing to see that PHP does not have a recursive delete function built in. So, I decided to write my own function. It works very well, it is small and it runs fast!

Well, here is the code:

# server credentials
$host = "ftp server";
$user = "username";
$pass = "password";

# connect to ftp server
$handle = @ftp_connect( $host ) or die( "Could not connect to $host" );

# login using credentials
@ftp_login( $handle, $user, $pass ) or die( "Could not login to $host" );

function recursiveDelete( $directory ) {
    # here we attempt to delete the file/directory
    if( !( @ftp_rmdir( $handle, $directory ) || @ftp_delete( $handle, $directory ) ) ) {
        # if the attempt to delete fails, get the file listing
        $filelist = @ftp_nlist( $handle, $directory );

        # loop through the file list and recursively delete the FILE in the list
        foreach ( $filelist as $file ) {
            recursiveDelete( $file );
        }

        #if the file list is empty, delete the DIRECTORY we passed
        recursiveDelete( $directory );
    }
}

The comments explain what is going on but, I will explain a little more right now. Basically, you pass the directory you want to delete to the function. The function will try to delete the file/directory that was passed to it. If the function fails to delete the file/directory, it will attempt to enter the directory and get a file list. The function then loops through the file list and calls itself by passing the file or directory from the list. It will repeat this until there are no more files or directories inside the directory you passed for removal. Once that is complete, it will re-attempt to delete the directory you passed to it.

Thats it! Very small script, yet very powerful. Be careful when creating these kinds of functions as you don’t want the function to accidentally delete more than you intended. Just a quick note about the function, make sure you include a trailing slash at the end of the directory! If you forget to, this function will try and delete the files and directories where the directory you passed is contained. It’s a good habit to get into anyway. I was flooding the FTP server at work with requests to delete directories I didn’t want to delete because I forgot to add the trailing slash! Good thing the file permissions stopped it!

Site Launched!

Hey everyone! My name is JR Tashjian and I am a Web Developer living and working in New York.

I started this blog because I wanted to write about what I do and what I learn as well as educate any readers wanting to learn more about Web Development. I will be focusing on the Back-End (server side) coding of projects using PHP and MySQL. I will also write a little about Front-End (client side) coding using HTML, CSS and JavaScript. As for post consistency, I haven’t set anything nor do I plan to. I will write articles as I have time but, I will aim for one or two posts a week.

Well, I am very excited about this launch! I hope everyone who reads my articles will find this site a valuable resource for learning Web Development. If you have any topics you would like me to write about or have a question you want answered, feel free to email and I will get back to you as soon as I can.

Check back often for updates! While your waiting, get the feed!