PHP: Abstract classes vs static classes; whats what?
In the past I’ve spent a great deal of time trying to understand the different between PHP5 abstract and static classes/methods. I find out, use the differences on whatever I’m doing, and the forget. No more. I will document my understanding here to help myself, and some day others, out.
Methods (not classes) can be defined as static (eg. not static class Oliver{} but rather static function talk()) in order to call them without going through an instantiated object. From my perspective, it makes code cleaner and less messy by wrapping related functions in a class wrapper instead of defining them globally. It should be noted though, that classes with static methods CAN be instantiated, and those methods can be called either statically (via the :: double colon notation, or via the -> right arrow notation on the instantiated object).
That takes us to abstract classes. Abstract classes CANNOT be instantiated. They can be the parent of a class which can be instantiated, but they themselves cannot be. So for example, if I have two types of users, RegularUser and AdminUser, I could create an abstract class User which defines method signatures (via the abstract keyword) like abstract function login($username,$password){} or I can define static functions which can be called (via the same rules as above). A new User object can never be created directly though.
So what does that mean in terms of real-world usage? Personally, if I don’t want a class every to be instantiated, such as a class that has utility functions or string manipulation functions, I will define it as abstract, and define all it’s methods to be static. If I have a parent object which should never be instantiated, I’ll do the same, but leave the method declarations to the child classes for the most part.
So then when do I use a normal class that happens to have static methods? I haven’t really. I’m sure there can be uses for it, but I’ve never found myself in a situation where I need to access an object’s method without the context of the object’s instantiation. Maybe it’ll come up one day, but as I’m moving closer and closer to a full mvc based coding life style, I have a feeling that I won’t find myself in that situation anytime soon.
Weird discovery: firefox converts $_SERVER, SF doesn’t?
This is definitely up there for me; a very weird discovery about how firefox and safari differ in the way the _SERVER array is returned.
print_r($_SERVER);
exit();
Run that code in a php script; then check the source in both safari and in firefox. For the path, try something like index.php?name=what’sup
The weird thing comes in with the fact that in Safari, the apostrophe isn’t converted/encoded, where as in Firefox, it is. I’m not really sure how I can explain this, and if I’m missing something, but it’s caused me a great deal of frustration and debugging. The only thing I can think of is that safari sends along different headers in the request than Firefox does, and therefore gets different results. I’ll look into it and update this post, but thought it was worth mentioning incase anyone else runs into the same type of problem.
php.ini error_log directive: finally fixed my code to make it work
I always ran into an issue whereby if i set the error_log location for an application/server using ini_set(’error_log’,'PATH’) it wouldn’t log it there. It would log it to whatever path was set in my httpd.conf file, whether it was the global error_log path, or one for a specific virtual host.
I searched high and low on the goog’s, but to no avail, I kept running into php.net bug reports about the behaviour not working. Then, I just tried something I should’ve tried a long time ago, set the write permissions properly (for testing, 777) and gave access to every user on my local machine (eg. on a mac, getinfo on the error log, and make it readable and writable by everyone), and success.
I’ve had a lot of headaches around this that usually ended up with me giving up, but I finally found a fix for my case of it
PHP Reflection class: a gem I found
In developing my own mash-up of a framework, drawing inspiration from a lot of different areas, I ran into an interesting hurdles.
Since my framework is MVC based, I ran into a problem whereby calling an action/method in a controller should only be fulfilled if the number of parameters passed in was valid. So for example, if I was dealing with a user’s model, and I wanted to return the email address for the user, I would normally access it via a url pattern such as: http://www.website.com/users/details/email/
On the server side, this would access the Users controller, the details method, and pass in a parameter with the value ‘email’. The method would then grab it from the db, and return it however it decided. The trick came in, however, as to validating the parameters that were passed to a controller’s action/method. So for example, http://www.website.com/users/details/email/oliver/ would pass the details method/action two parameters with values ‘email’, and ‘oliver’.
But my method/action only accepts one. So what should happen? Well ideally, a 404/error page should be pushed out, but how would PHP know that the parameter count doesn’t match? You have two options. One is very intrusive, and the other is best thing ever.
1) Intrusive: in every action, hard code something like:
if(func_num_args()>HARDCODED_NUMBER)This would mean every action/method would need to do this check to make sure the right number of param’s were sent in (this doesn’t even take into account the minimum number of req’d parameters; only the max allowed.
// redirect
2) The best way ever: before making a call to controller’s action use the Reflection class.
This class allows you to check the parameter requirements of a call BEFORE you actually make it. So using php5’s Reflection class, you can check to see how many parameters are required at a minimum (excludes required praams’), how many are the max, and even more fun stuff. This allows you to centralize the error handling for controller calls to the dispatcher (my naming convention for the class/method that actually makes the calls to an action/method), keep your code very clean and clear.
I did some checking, and it seems using this class isn’t too expensive since this information is contained by php be default; it’s just that this extension contains the API for actually accessing it.
It’s a win-win situation as far as I’m concerned.
Framework: S^3 (aka S cubed): I’m calling it Smart Setting Selection
In working on a custom framework (that’s uniting a lot of the best of the existing ones, but keeping it lean and cutting out what I don’t need), I ran into a configuration roadblock which caused me to write some nifty code.
Basically, this framework has a bunch of settings/config files, and some of the files (ini format, using parse_ini_file) are seperated by the following keywords:
local,development,staging,production
Basically meaning, if I have a configuration setting that is supposed to mean something like ‘maxTimeout = 500′, I could, and in a real world application, would have that setting store different values based on which server the code base is being run on (eg. my local would be a lot higher, but the other ones like the production would be much lower for optimization purposes).
This lead me to write some nifty code that will parse all the ini files, and then when I want to retrieve something, it does a check for one of those 4 reserved words. So a real world example would be something like this:
An ini file is parsed and has the following format:
Array
(
[local] => Array
(
[name] => TEST
[cookies] => 1
)
[production] => Array
(
[name] => TEST
[cookies] => 1
)
)
When doing a call to the function and asking for the setting ‘name’, recursively as it moves it’s way down the settings array, it’ll look to see if it contains a keyword of local, production, etc., and if it does, automatically set the value to that array/value. This will be clearer once I OS the framework which won’t be for a while, but to understand it from a code perspective, check this out:
public static function getDetails() {
$details = self::$details;
foreach(func_get_args() as $argument) {
$details = $details[$argument];
if(array_key_exists(Request::getServerRole(),(array) $details))
$details = $details[Request::getServerRole()];
}
return $details;
}
This means that my server will automatically pull the right setting detail based on what server is doing the requesting. I just need to setup my ini files so that if a setting needs to be different based on which server is being loaded, it can be.
Professional CodeIgniter: Review (part 1)
So far, I’m done about half of Professional CodeIgniter by Thomas Myer. As you guessed, it’s about the php, MVC framework CodeIgniter. While I’ve spent a lot of time online at the documentation, tutorials, etc., I’d preferred to grab a book on it (the only one I could find that’s available) to get a more formal introduction.
In terms of how it’s written, I was very impressed by it very early on. The language is very clear and concise, and Myer does a great job of walking you through a very real world example. I was actually blown away by how well he can articulate fairly advanced concepts. However so far this was the highlight with some major let downs.
For me, I came into this expecting a book on how CodeIgniter worked, how it’s structured, it’s benefits, etc., but after having read half of it so far, it’s become much more like a basic php web development tutorial. There is a recurring tutorial that is themed throughout the book of how to setup a rudimentary e-commerce site. When the tutorial begins, some CodeIgniter specific code is presented, with outlines of the helper classes, organization of a request/mvc separation, etc., but very quickly, most things specific to the framework are forgotten, and CSS/JS/PHP becomes the focus.
Additionally, the focus seems to be targetted at a beginning. Perhaps that was the intention, but it was a real disappointment for me. This framework is exceptionally powerful, and while it’s seeming to operate much more like a library than a framework such as CakePHP, it has tons of usage, most of which doesn’t seem to come through in the first half. A lot of time is devoted to making ajax calls to a controller (understandably a notable topic, but not specific much to CI), pages and pages of CSS (at one point there was a 3 page stint of pure css code, which didn’t seem very relevant as it’s a PHP/CI book), and even JS.
I believe I understand the intention; Myer wants to take you from concept to delivery, and show you how everything in between fits together within the CI framework; however because of this, I’ve felt that the power of CI has been left behind for me to figure out in their documentation.
While CI does push convention over configuration, it does seem to come across as a very strong and powerful library rather than a framework (with some pre-req’s that push it into the latter category). This isn’t necessarily a bad thing, but since it’s the case, I would expect more of the library to be explained, and how it could be useful, rather than walking through a tutorial that is targeted much more at the new php developer delivering a larger project than they’re used to.
I’ll follow up with my second half of the book review shortly.
Caching is easy; releasing them isn’t.

When developing web app’s that are going to even moderately scale, caching will be your saviour. Whether it’s assets such as images, js files, css, or data sets such as records from a users table, xml files, or whatever else, caching is key.
But when dealing with data sets, such as user records, posts, comments, or whatever else, caching them will not be the hard part; knowing when to release/renew them will be. For example, if you were to cache the 10 most recent comments for a blog post to prevent sql hits to your database, there are a few times you’d need to release/renew them:
- A new comment is added
- A comment is deleted
- The pagination changes from 10 to some other number
- The blog post is deleted
While this may not seem like a big deal, this is just one situation in which the comment data is used, and just one type of data set. Image 20 different tables (common) and more than one place where a data set is shown (very common; for example a widget on your homepage that shows the last 5 comments for all the blog posts, etc.)
Having a clear naming convention for your cache keys is very important; probably the most important in terms of keeping your caching layer organized. It makes it easy to track cache’s that aren’t working properly when the key’s are something like ‘User[1]->Comments(last 10)’ rather than a sha1 representation of the sql query that produces the results.
Just a tip.
php’s foreach on a string? you can do that.
Reminder to self:
Normally, to do a foreach must be something like array(”oliver”,”nassar”). I’ve run into a situation where I didn’t if a variable, lets say $wtf, was an array or just a string. Running foreach on a string results in a notice like “Warning: Invalid argument supplied for foreach() inĀ /random/file/path.php on lineĀ #line-number“.
Just write this, and you should be good:
foreach((array)$unknown as $key=>$value)
echo "go nuts.";
?>
What framework does php.net use? Answer: I don’t know.

I’ve been looking at frameworks a lot lately. Mainly for an upcoming project, but also to getting a better understanding of MVC based development, as well as components/helpers for web develop
ment. That made be ask the question, what framework does php.net use for it’s documentation/downloads site?
I read somewhere that Rasmus Lerdorf, the guy who invented php, who went to University of Waterloo, by the way, felt particularly fond of Code Igniter. I’ve looked at it, and heard great things mainly due to it’s ease of use, but echoing Rasmus’ thoughts, if feels much more like a library than a framework, at least to me.
That’s not a bad thing; Rasmus’ meant that positively. I personally don’t think you should be relying on an open source distribution to do the thinking for you. I’ve run into many people who claim to know javascript, but what they really mean is, is that they know how to use a framework like MooTools, JQuery, or YUI. Knowing JavaScript takes much more time, and takes a higher discipline. It’s not for everyone, but it’s not different than someone knowing how to use Dreamweaver or Frontpage, and advertising that they know how to develop website. You don’t know how to develop website, you know how to use a program that writes the sites for you, much like if you’re using a framework, you know how to use an open source distribution to help you write a website.
I’ve been playing a lot with CakePHP lately, and that, in my mind, is a true framework. Everything is native to Cake. Their site is very intimidating, and their framework is VERY expansive, but it’s therefore very powerful. I’m not sure it’s exactly what I was looking for, but it’s given me invaluable insight into framework development for php.
This then leads me back to the question of what php.net uses. My guess is a custom framework; not symfony, or cake, or CI, or zend or any of those guys (probably because they came about way later than php.net), but I’d be interested to know what they do use, and if they’d open source it. For now, I’ll keep working on my own framework that is geared towards being lean, and requiring me to do a lot of the heavy lifting for maximum flexibility. Hopefully I’ll open source it someday, and it’ll be able to meet the needs of people like me for whom Cake was too much, and CI (Code Igniter) was too little.