Posts Tagged ‘PHP’

PHP Namespaces and Exceptions

Thursday, May 31st, 2012 | Programming

Recently, I was trying to catch an exception that was raised when someone entered an invalid date string. Every time I tried it however, it would continue to throw the standard Symfony2 error information, rather than executing my catch block.

try {
    $date = new \DateTime($str);
    return $this->setDateOfWork($date);
} catch (Exception $e) {
    return false;
}

After a good thirty minutes of being puzzled, we eventually worked out what it was – because we were working within a namespace, we needed to call the Exception object, which is after all just another object, from the global namespace.

try {
    $date = new \DateTime($str);
    return $this->setDateOfWork($date);
} catch (\Exception $e) {
    return false;
}

This applies to any other types of Exceptions you’re trying to catch too – make sure you’re in the correct namespace!

Essential Drupal modules

Wednesday, May 30th, 2012 | Limited, Programming, Tech

Drupal is a great PHP-based CMS (content management system), but its true power is only unleashed when you use the modules system. Out of the box, Drupal provides basic functionality for creating and publishing content with additional functionality that can be added by installing modules, you have a far more powerful system.

In fact, most of the core functionality of Drupal is provided via modules as well. Drupal ships with a series of “core” modules which, should you wish to, you can disable. So if you don’t want the menu system, search, taxonomy or the help system, you can turn all of these off.

Beyond that though, Drupal can be extended significantly thanks to its reach ecosystem of modules (or plugins if you will) that provide significantly more functionality than the core system ships with. While you’ll need to find the right modules to match your needs, there are several that are considered the staple diet of Drupal developers.

Chaos Tool Suite
It may not look like anything special to get started with, but CT Tools provides an expensive range of APIs and systems which make developing with Drupal easier. It’s a platform to use when developing your own modules but also serves as a dependency for many other modules.

Views
The most installed module of any on the Drupal website, and it’s easy to understand why. Views is an incredibly powerful module which allows you to create custom pages that do various tasks – such as listing out a content type, sorting things a certain way, creating archives and many other tasks.

Entity Reference
At some point you will probably want to reference one entity to another. For example, on the Know Leeds website we have places and we have restaurant reviews. For each restaurant review we write, we want that to be linked to a certain restaurant (a place), and we do this with Entity Reference.

Pathauto
If you think you’re getting an exciting Greek named module, think again – it’s just the words path and auto put together. But it’s still a very useful module as it automatically creates friendly URLs without you having to type something in.

By default, Drupal won’t create a node reference for an article, it will just use the ID. You can override this by typing in something like article-title, but Pathauto will do this automatically. It’s good to install this from the start as it allows you to set up patterns for articles, categories and other systems so that you have uniform URLs across your site.

CAPTCHA and reCAPTCHA
reCAPTCHA is a fantastic took that stops spam and helps translate books at the same time. Using these two modules you can add reCAPTCHA to your site to stop spam bots registering accounts.

Taxonomy menu
This allows you to build an automatic menu out of a taxonomy set. So if you have categories as part of your taxonomy and you want to create a menu that automatically lists each category, this module will do it.

Drupal basics in under five minutes

Tuesday, May 29th, 2012 | Limited, Programming, Tech

Drupal is probably the best PHP-based CMS (content management system) on the market today. However, because it has a somewhat steeper learning curve than other systems, where you can just install and start creating content, it is easy to get frustrated with it and give up.

However, a short amount of time getting your head round the basics should be enough to show you that Drupal has some really powerful features which make it a far better CMS than those that simply allow you to drop text into pages.

We used Drupal to build Know Leeds and it allowed us to quickly and easily put together a functional site that allowed the non-technical contributors to get to grips with the system.

Content types
Because most people are familiar with WordPress, I’m going to use that as a comparison throughout this article. If you’re not familiar with WordPress, don’t worry, because most, if not all of the terms used are generic concepts that you will be able to understand anyway.

In WordPress, you have two types of content – posts and pages. Posts are the bread and butter of what was traditionally a blogging only system. Pages, are similar, but are static and don’t go into the date-based archives.

In Drupal, you get to define your own content types. It comes pre-configured with an article (similar to a post) and static page content types, but where you go from there is up to you. There are two good examples of where we used this in Know Leeds.

Firstly, we added a content type for “Restaurant Review”. This is similar to the Article content type, but we wanted to add some additional fields to Restaurant Review that didn’t want to be in Article – a star rating and a categorisation of what type of food the restaurant served.

Secondly, we added a content type for “Place”. We offer listings of local bars, clubs and restaurants on the website and if you think about it, an entry for one of these is basically just a piece of content. But with different needs than an article – we need address, phone number, email address, etc. So we created a custom content type for that too.

Fields
As I discussed with our custom content types, we wanted to customise the field types on our content types. In WordPress there are a number of fields – title, body, published date, categories, etc. In Drupal, you have the same thing, but you can create your own fields and match them to each content type.

So for the Restaurant Review content type we added a star rating field. This allows the editor to enter a numeric value between one and five. We also added a Cuisine content type which allows them to pick what kind of food it is. This works just like the WordPress categories system, except we can have multiple types of categories and we can pick which content types they apply to!

Taxonomy
In WordPress, there are two types of taxonomy – categories and tags. In Drupal, surprisingly enough, you can define your own. As I’ve already discussed, we created a Cuisine taxonomy and added a list of different terms (or categories if you will) such as French, Italian and Steak House.

Drupal allows you to create as many different categorisation systems as you wish and apply them to the content types as appropriate. We only wanted Cuisine to apply to the Restaurant Review content type for example, but Category might apply to both Article and Restaurant Review.

Blocks
Units of content which can be placed somewhere in your layout are called Blocks. The nearest equivalent to this in WordPress is the “widgets” system where you can drop widgets in and out of the sidebar.

Drupal comes with some standard blocks such as user login and search form, and many of the modules you can add into Drupal will add some blocks too – adding the forum module will add an “active forum topics” block for example. Of course, you can create your own custom blocks too.

You can then define where these appear – first sidebar, second sidebar, footer, navigation menu, etc, by selecting their position from the blocks menu. You can even do this on a theme by theme basis – on one theme you may want the search form to go in a sidebar for example, in another theme you may want it to go at the top or bottom of the page.

Unlike the widgets system in WordPress though, everything is a block in Drupal! Even the main page content so for some reason if you wanted to make your footer text display in the centre of the page and your main content display in your sidebar – you’re just a couple of clicks away from that!

Menus
Menus probably need the least explaining of all – it allows you to create menus which people can navigate around the site with. It is worth noting though, that items don’t appear in the menu automatically – you have to request that a piece of content (usually a static page) is given a menu link when creating or editing that piece of content.

Of course, you can create as many different menus as you want, assign different content (or any other links you want to add!) to different menus, and have the menus display in different places around your layout using the blocks system.

Conclusion
I hope this has presented you with a quick introduction to the fundamental concepts of Drupal. It is far more customisable that most other popular content management systems and as such has a steeper learning curve, but far more flexibility once understood.

Primary key ranges in Propel ORM

Wednesday, May 23rd, 2012 | Programming, Tech

If you’re using Propel ORM, you may want to select a range of primary keys. According to the documentation, you should be able to do this using code similar to the following.

BookQuery::create()->filterById(array('min' => 1, 'max' => 100));

However, what you find you get is that will return books with the ID of 1 and 100, but nothing else.

That is because Propel does not support ranges on IDs. This has been noted on the Propel GitHub issue tracker and will be resolved at some point in the future, but until then you have two possibilities.

Firstly, if you’re only looking to specify one value in the range, you can pass a criteria constant to filter by that.

BookQuery::create()->filterById(30, \Criteria::GREATER_THAN)->find();

You can also use LESS_THAN in the same way. Or, if you need a range with both ends specified, you can resort to the where() method.

BookQuery::create()->where('id BETWEEN 1 AND 100')->find();

Though that method requires you to use the database column names, rather than the PHP names used in Propel (yours may be the same, but I often rename mine for legacy reasons).

Migrating away from register globals

Friday, April 27th, 2012 | Programming, Tech

If you are luckily enough to work in a Web 2.0 start up, you probably won’t have to deal with too much legacy code. But for the rest of us, we can often find ourselves working with code which can be even decades out of date.

One of the big issues in PHP has been the deprecation of register globals. Of course, this happened quite a long time ago, because the idea of register globals was just plain stupid, but recent versions of PHP (5.3 onwards), will now throw a deprecation error.

So, we need to find a way to turn register globals off.

The end solution is of course to refactor the code so it doesn’t use register globals at all. Anything short of this is going to be a security nightmare, it’s like a ticking time bomb sitting on your server. But until then, there is a way you can emulate it in your PHP code while you work to get rid of it, allowing you to turn the register global settings off.

All you need is something like this in your code.

foreach ($_REQUEST as $key => $val) {
	$$key = $val;
}

Install dev packages with Composer

Monday, April 2nd, 2012 | Programming, Tech

Sometimes, you might install your dependencies via composer but find that the tests don’t work for it. You could get an error similar to the following.

phpunit
PHP Fatal error:  Class 'Symfony\Component\Yaml\Yaml' not found in
/home/example/Gherkin/src/Behat/Gherkin/Keywords/CucumberKeywords.php on line 31

This could be because if you have just run composer install, it will only install the main packages, but some packages could be specified as dev only. You may find a “require-dev” section in the composer.json file.

If you do, you can install the packages using the following flag.

composer install --dev

This will install the development packages as well, which should allow you to run the tests.

Compiling APD on PHP 5.3

Monday, April 2nd, 2012 | Programming, Tech

If you try and compile APD on PHP 5.3, you may get an error similar to the following.

error: 'struct _zend_compiler_globals' has no member named 'extended_info'make: *** [php_apd.lo] Error 1

This can be solved by modifying a few of the APD files. To do this, you need to download the APD archive file and uncompress it.

Then make the changes as detailed on the PHP bug tracker. Once this is done, it should install as normal.

phpize
./configure
make
sudo make install

APD should now be installed.

Leeds PHP User Group

Friday, March 30th, 2012 | Life, Tech

Last week, I finally made it down to the Leeds PHP User Group.

The meeting consisted of a talk by Lorna Mitchell on Git, Github and Open Source. It didn’t tell me anything that I didn’t already know, but it was interesting none the less. They also provide free food at their meetings, so I then regretted eating before I went 😀 .

By a perhaps unfortunate coincidence, the next day one of my friends sent me a contact they recommend I speak to about my career. The name rang a bell – turns out the recruitment agency had in fact been sponsoring the event and she was there – if only I had known 24 hours earlier I could have introduced myself in person! Still, there is always next month.

Hashing passwords in PHP

Thursday, March 8th, 2012 | Programming, Tech

If you store passwords as part of a PHP script, you may be using md5() or sha1() to hash the password. This is common practice, but you may be suprised to know that actually, the PHP manual recommends against it.

The reason is that they are both fast but relatively insecure hashing algorithms that can be brute forced by modern computer systems if they get hold of the strings. A better approach is to use the crypt() function, which is a little more expensive in terms of resources, but worth it for the increased difficultly you create for any potential hackers.

View all PHP scripts currently running

Friday, February 24th, 2012 | Life, Tech

Need to get a list of all the PHP scripts currently running? Actually, this technique works for everything, you just need to change the argument you pass to grep, but for the purpose of this example, I’m going to say we’re looking for PHP scripts.

ps aux | grep php

This will then produce a list of all the scripts. The ps aux command gives us a list of every processing running on the system. We then pass this through to grep and search for what we want – in this case processing which contain “php”.