Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

Monday, April 16, 2007

An easy way to add (web 2.0 like) tags to your posts

One of the features that is closely linked to the web 2.0 developments is the use of Tags. Tags are short phrases (/words) that describe the article they accompany. Tags are great for categorizing posts and give the reader of an article information on it's subject instantly.

You see, for Tags to be effective it would be best to minimize the variety being used. If all tags concerning programming have a tag 'programming' attached to them, we could use that tag to effectively categorize those posts. Using standard tags for posts helps us create a more structured and better organized category system. The problem however is that you can't remember all the tags you already use and you probably don't have enough room (or want for that matter) to show all the tags in a row.

Using script.aculo.us however this problem is solved very easily! First of all, if you didn't know this already, Scripaculous is an open source Javascript framework. It used the Prototype framework and it provided many graphical effects and other powerful tools to it's users. One of the things it offers is an Autocompletion class, which we are going to use to make our lives a lot easier. Basically autocompletion presents matching options while the user is typing. The user can click the options (or use his keyboard) to select an option after which the text is inserted in his input field. Go to this Scriptaculous demonstration to see what I'm talking about.

First of all we need a database that contains the tags. This database must at least contain these fields:
- id (int, primary key, auto_increment)
- tag (varchar, unique)

Then we need a table to link tags to posts:
- tag_id (int)
- post_id (int)

Next, let's set up the input page. First of all we need an INPUT field, e.g.:
<input name="tags" id="tags" value="" style="width: 300px;" type="text">

Next we need an invisible DIV that Scriptaculous will use to show it's autocompletion results, e.g.:

<div id="auto_complete" style="display: none;"></div>

Now on to the Javascript!
For the sake of easy testing, let's add a local array containing the tags that are already used on the website (the tags the autocompleter will use):
var tags = new Array('news', 'websites', 'links', 'programming', 'php', 'mysql', 'apache', 'games', 'hardware', 'holiday', 'business', 'ICT', 'music');

Be sure to add that inside a Javascript block!

Here comes the magic! Below the form field containing the tags, add the following Javascript function (inside a javascript block:
new Autocompleter.Local('tags', 'auto_complete', tags, {});

This function will add the autocompleter. It will use the INPUT field 'tags', fill the DIV 'auto_complete' with results and use Javascript array 'tags' as it's source. The {} at the end signify the options array (empty for now).

The above works! However there is a small problem with it.. It will only allow you to add one tag! After that, autocompletion won't work.. Luckily, Scriptaculous can fix that! In the empty brackets ({}) at the end, add the following: tokens: ','

Or make it like this:
new Autocompleter.Local('tags', 'auto_complete', tags,
{
tokens: ','
});

Now you can add multiple tags and seperate them using commas! How neat is that! You can also set more options (for instance partial searching, minimum characters for autocomplete to start, etc), which are described here.

Of course it's also possible to load the autocompletion tags using Ajax. I think however it would be better to render the tags array using PHP at page load, because of performance (each Ajax request takes time, while the tags won't change..).

Click here to view my demonstration page for the above!

Next is the PHP part!

I won't go into much detail here.. This part basically requires 2 steps:

  1. Split up the tags;
  2. Save each one. If they already exist in your table, only add a link from the new post to the tag, if they didn't exist add the new tag and link the post to it.
Splitting up requires a small 'heads-up': scriptaculous will allow whitespace after the seperating comma, so you need to watch out for that aswell. Here's how:

// Strips whitespace at the beginning of a string
$_POST['tags'] = ltrim($_POST['tags']);

// Splits up the tags
$tags = preg_split('/[ \t]*,[ \t]*/', $_POST['tags']);

Now all you need to to is loop through $tags and store the tags (as described in point #2). Make sure you first check if the tag already exists! If it does, only store the link from this post to the tag! If it doesn't, add the tag, then get it's id (mysql_insert_id()) and then store the post->tag link.

On great thing to do with tags is create a (Web 2.0) tag cloud!

Also be sure to check out my demonstration for the above!

Happy web 2.0'ing!

Thursday, March 29, 2007

Further endeavours into baking Cake(PHP)

I have been playing around with CakePHP for the past several days. I've started work on two projects using Cake; a financial administration system (for my company) and a redesign of ITKA's iCMS Content Management System (link is in Dutch). I feel that I'm learning CakePHP quite quickly, which of course is a good thing. A word of warning though to other aspiring Bakers (see, I've already copied their slang!): CakePHP takes somes time to master, and I really wouldn't advice anyone using it without complete knowledge of how the system works.

The point is that CakePHP takes convention over configuration. Personally I love this concept, what's the point in being able to configure everything if you could also just play by the rules. You see, reading up on configuration in the manual is just as time consuming as reading up on Cake conventions. Furthermore Cake offers configuration exactly where you need it. Who cares that you need to access functionality via the controller (e.g. www.example.com/posts/edit/1) if that is only visible to the user. Routing is a powerful CakePHP function that is quite similar to mod_rewriting, except that it is more powerful. You can easily prefix /admin/... to administration functions and make pretty urls like www.example.com/blog/my-first-post using routing. Even if you use exceptional names and stuff the standard Cake conventions can be manually overwritten, it's all possible!

The one major question that currently still has my concern is performace. If you print_r() some objects used by Cake during runtime you can see that they are truly massive containing information on the database tables, related database tables (and models), etc. etc. Anyone have any thoughts on this?

For now I have got some tips for beginning Cake developers (like myself).

  1. Use scaffolding and only scaffolding when you are designing your database structure. At the start of a project, first build all the necessary models, controllers and db tables. Link them using Cake's $hasMany/$belongsTo/$hasOne/etc. functions and check to see if all relations work properly (i.e. when viewing one thing, you get 'related [other things]'. Scaffolding will really help you out here, as you can instantly check everything (no need to rewrite any HTML, etc).
  2. At the start of an application get your internal structure right. Like mentioned in #1, use scaffolding to get your database/model relation structure right. In the early stages it's a) easier and b) less time consuming to set everything right for final implementation. Consider Cake's MVC approach: you need to seperate data, business logic and presentation. First get your data and data structure right, then add business rules and logic and only at the end worry about presentation. The method is not the same as the MVC approach (which is only about code seperation). This is an engineering approach that takes on different parts of the project one-by-one, in a logical order.
  3. Learn by experience. This by the way goes for any programming language learning and is generally the way I advice people to learn programming. The point is that programming isn't something you know, it's something you feel. It's a creative process! Building a program can be done in many different ways and quite often there isn't even a best way. You need consider your alternatives, choose and finally go with that choice. You will always encounter new problems as a developer and so you will always need to come up with creative solutions for those problems. The best way to learn to do this is by gathering experience. Create a small but challenging project for you to take on, take it on and come up with solutions for the problems you encounter. Search the web, talk to other developers on forums, but get your problems solved. CakePHP, due to it's extremely intuitive conventions, is perfect for this learning method. Finding the answer you are looking for in Cake is easy as for some reason you just know where to look.
As you can see I am very enthusiastic on Cake. I'm looking forward to finishing up the applications I've started work on. Those projects should provide me with a sufficient knowledge base for implementing CakePHP in customer projects, which would be great considering the development time Cake saves you :)

Sunday, March 25, 2007

CakePHP: Setting up the ACL tables

I am currently exploring my way into CakePHP. Have to say I am really enjoying working with it. Everything is starting to get clearer to me step by step.. Just now I've been struggling with getting the ACL tables properly set up. The manual suggests that I simply ran the /cake/scripts/acl.php scripts from the command line. I appeared that this was easier said than done, so here's what I eventually came up with:

  1. Open your command prompt (Windows Key + R);
  2. Move to your PHP directory (which contains php.exe)
  3. Run the following command:
    php.exe -f "x:\webroot\cake project\cake\scripts\acl.php" initdb
The script now properly executes and creates the aros, acos and acos_aros tables. Please make sure your database is properly configured and for the rest just follow on what the manual has to say!

Friday, March 23, 2007

My own first taste of CakePHP

I've started experimenting with CakePHP yesterday. This was actually the first time I've used any framework and even though I don't completely grasp how it works yet, I was already pretty impressed by what I could build up in just half an hour (using Sitepoint's CakePHP tutorial).

The idea with CakePHP is as follows:

Cake is a rapid development framework for PHP which uses commonly known design patterns like ActiveRecord, Association Data Mapping, Front Controller and MVC. Our primary goal is to provide a structured framework that enables PHP users at all levels to rapidly develop robust web applications, without any loss to flexibility.
Personally the main advantages I take out of this is that using such a framework forces you to use a certain approach to programming, which usually means following a good practice one. The MVC (Model View Controller; seperation of data, output and business logic) approach brings more structure into your applications and with the help of all the built in functions provided by CakePHP is very powerful, yet also quite flexible!

I recommend any PHP developer with some spare time on their hands to take a look at this tutorial and the CakePHP website. The website contains a pretty elaborate manual with detailed installation and configuration instructions (don't worry, takes about 5-10 minutes). Getting started with CakePHP with just the manual was a bit difficult though, so that's why I recommend the Sitepoint tutorial. This tutorial will take you around 30 minutes to complete and really gives great insight in what CakePHP (or a development framework for that matter) is all about.

Update #1: acutally this post on Giga Promoters Blog has some very interesting things to tell about CakePHP before you get started.

Update #2: another great tutorial by IBM. Actually part of a series. (requires registration with IBM, free).

Thursday, March 22, 2007

Why you want Object Oriented Programming in PHP

First let me explain what the issue is around Object Oriented Programming (OOP). Traditionally (from the beginning of the computer era), programming was done by combining conditional statements with GOTO blocks to create a program flow. In the early '70s a Dutch computer scientist Edsger Dijksma strongly advocated the use of procedural programming, which means abandoning GOTO statements and creating a sort of chronological program flow in your code (from top to bottom). This style has been widely adapted and for most people is the way they program PHP applications. It is however already a thing of the past. Most modern programming languages are based on an OO approach and don't even allow for procedural coding anymore (for instance in languages as Java, C++, C#, Python, and Ruby). Explaining OOP goes beyond the scope of this article, so for understanding OOP in PHP I'd like to point you in this direction. For now let's just say that OOP is about creating relatively small objects with specific functions that interact with each other to form a complete application.

Typically, the main advantages of OOP are:

  • Reusability of code; a well designed object has only one specific function and is therefore completely independent of the environment it is placed in and thus can be reused easily.
  • Clearer structure of code; again a well designed object has only one specific function which means that all the code supporting that function is located in one place which increase maintainability.
A major disadvantage of OOP is that it requires more lines of code and is therefore more time consuming to produce.

In PHP we as developers are left with a choice. Typically, anyone who started out with PHP without any (OO) programming background will have started with learning procedural coding. Most tutorials on the web only cover procedural coding and quite honestly, the old fashioned way is just easier to use in many situations (for instance in small applications, or when you just start out with PHP).

However (here comes the wise lesson) Object Oriented Programming in PHP is definitely the way to go for any serious PHP developer taking on serious projects. For the past 8 months my web development firm has been working on a huge project for a real estate agent. The application takes care of many aspects of the clients administration, publishes it's information to multiple people (each with different clearances) and in multiple formats (web content, PDF, RTF). Using OOP in projects such as this is so incredibly superior over using procedural coding. Using OOP, we for instance model a real estate object (a house...) as a PHP object. The (PHP) object contains over 60 variables (all stored in a MySQL database but intelligently retrieved by the object) and many functions that allow the object to update it's data and return information on itself based on the users clearance levels. The data itself can be interpreted by either our web content generator object, or by our PDF generator object, no changes required. This goes for all the little parts the application has and you wouldn't believe how much time it has saved us in making small adjustments and adding small new features.

Doing this project in procedural code would have been horrible and messy. Just imagine having new additions to your project specifications on a weekly basis for several months and jotting all those things in between the already existing code using if/else statements etc. in procedural coding. You would probably go screaming mad about the PHP files containing more than 500 lines of code without any clear structure in them..

What's more, many of the classes we have designed for this project are useful in other projects as well (this actually already proved true). Furthermore we are experiencing nice and clean work divisions since we switched to OOP which definitely increased both our productivity and efficiency.

The thing is that the extra work needed when using OOP will be earned back with huge interest in a little while. Maintenance time is dramatically reduced, there is no more code overlap in your application and you (and your fellow programmers) will work more efficiently due to clearer work divisions and structure. Switching to OOP is really not that difficult, given the many tutorials (for instance this one, by Harry Fuecks) and will save you valuable time and most of all make your life easier.

If you are still not convinced I strongly suggest you read Harry Fuecks' tutorial mentioned in the previous paragraph as it will point out more advantages to you. Also you mind want to start learning OOP because of the PEAR project (standard libraries written in OO PHP, designed to really make your life easier by offering standard functions in freely available packages). Feel free to ask questions if you have any!