PHP Classes
Further to yesterday’s comments on Javascript libraries, today I would like to touch on the server side of things and focus on PHP.
PHP, like Javascript is a object-orientated scripting language. This means classes can be created and instantiated when needed. However, online resources for PHP most often fail to treat it as an OO language and instead prefer to offer tutorials and solutions based on the procedural side of things. This is a big mistake and makes the code hard to port and reuse.
If you take the time, you can create classes which perform many tasks and which you can cleanly use over and over again. You can create a library of such classes and use the ‘require_once’ construct to include them in your code. All very straightforward. An example of a predefined class is the PDO class. This wraps around your database and provides a nice consistent interface to connecting to your MySQL DB. PHP has many such classes which come pre-installed with the package, depending on the version you are currently using.
Besides creating your own classes and using those already defined as part of the PHP package, there are sites where people upload classes they have created. With care you can use these classes and increase the modularity of your code. For instance, it is possible to find classes for standard form manipulation, emails systems, payment systems and others.
There is not much you cannot pack into a PHP class and keep for reuse later. Not only is this design methodology good for reusing your code, it also promotes good coding practices and reduces bugs due to the increased amount of testing on each instantiation of the class.
Another step in good website programming practices (after reusing PHP classes and standard Javascript libraries), is to decouple your logic from your site design. I shall leave this discussion for tomorrow, but in the meantime you can read about Smarty to give yourself a headstart.