7Reusable CodeIgniter Model

Reusable CodeIgniter Model

I’m a big fan of the CodeIgniter PHP framework and would highly recommend it to anyone looking to start up a new project. Whilst there are now likely much better options such as Laravel, CodeIgniter is still a useful and powerful framework and a perfect option for you to¬†get your head around the MVC concept.

One thing that just about all CodeIgniter beginner tutorials teach you is to create a model and then to write very specific methods within that class. For example you may have a model for courses in which you’d write a method called ‘get_all_courses’.

That’s great, and it works, but it could be much better. Unless that method is providing any different functionality to any of your other ‘get_all_something’ methods then it’s pretty pointless. Instead you should extend the core CI_Model class and implement your generalized methods there. That way you’ve instantly got access to a whole load of great methods and you still have the ability to override them in your model classes for any special functionality.

Here’s a quick example class I wrote which extends the core CI_Model class. If you make all of your models extend from this new class you’ll be able to do things like this regardless of what model you’re using.

<?php
$this->coursemodel->get(array(
    "course.level >" => 5
), 5, 0, "course.date_starts ASC");

Much easier, right? Here’s the full class

<?php
class AppModel extends CI_Model
{
	function __construct()
	{
		$this->fields = array();
	}
 
	function init($tableName = "", $primaryKey = 'ID', $selectWhat = '*')
	{
		$this->tableName = $tableName;
		$this->primaryKey = $primaryKey;
		$this->selectWhat = $selectWhat;
 
		if($tableName)
			$this->fields = $this->db->list_fields($tableName);
	}
 
	function get_table_name()
	{
		return $this->tableName;
	}
 
	function get_columns()
	{
		return $this->db->list_fields($this->tableName);
	}
 
	function filter_result($result = array())
	{
		foreach($result AS $rowKey => $row)
		{
			foreach($row AS $key => $val)
				$result[$rowKey]->$key = stripslashes($val);
		}
 
		return $result;
	}
 
	function get_fields($alias = false, $customAlias = '')
	{
		$fields = array();
 
		// Custom alias?
		if(!$customAlias)
			$customAlias = $this->tableName;
 
		foreach($this->fields AS $field)
		{
			if($alias)
				$fields[] = "`" . $this->tableName . "`.`" . $field . "` AS " . $customAlias . '_' . $field;
			else
				$fields[] = "`" . $this->tableName . "`.`" . $field . "`";
		}
 
		$this->select_fields = $fields;
 
		return $fields;
	}
 
	function num_rows($where = array(), $limit = 1000000, $offset = 0, $order = '', $options = array())
	{
		$options['num_rows'] = true;
		return $this->get($where, $limit, $offset, $order, $options);
	}
 
	function get($where = array(), $limit = 1000000, $offset = 0, $order = '', $options = array())
	{
		// Select
		$this->db->select($this->selectWhat);
 
		// From
		$this->db->from($this->tableName);
 
		// Is this a search?
		if(is_array($where['keywords']))
		{
			// Load default search fields?
			if($where['search_fields'] == null)
				$where['search_fields'] = $this->searchFields;
 
			// Extract
			$searchFields = $where['search_fields'];
			$keywords = $where['keywords'];
			$where = $where['where'];
 
			// Loop keywords
			if(count($keywords))
			{
				$this->db->open_bracket("AND", $this->tableName);
				foreach($keywords AS $keyword)
				{
					foreach(array_values($searchFields) AS $i => $field)
					{
						$this->db->or_like($field, $keyword);
					}
				}
				$this->db->close_bracket();
			}
		}
 
		// Where constraints
		if(count($where) > 0)
		{
			$arrayFields = array();
 
			// Loop through
			foreach($where AS $key => $val)
			{
				if(is_array($val))
				{
					$subSQL = '(';
					foreach(array_values($val) AS $i => $v)
					{
						if($i != 0)
							$subSQL .= " OR ";
 
						// Does it have an operator?
						if($this->db->_has_operator($key))
						{
							die("This bit needs improving, but it's a rare thing this ever happens - when the lookup value is an array and the key contains an operator... not yet supported!");
						}
						else
						{
							$subSQL .= "`" . str_replace('.', '`.`', $key) . "` = " . $this->db->escape($v);
						}
					}
					$subSQL .= ')';
 
 
					//$arrayFields[$key] = $subSQL;
					$this->db->where($subSQL);
				}
				else
					$arrayFields[$key] = $val;
			}
 
			$this->db->where($arrayFields);
		}
 
		// Order
		if($order)
			$this->db->order_by($order);
 
		// Limit
		if($limit)
			$this->db->limit($limit, $offset);
 
		// Any joins
		if(count($this->joins))
		{
			foreach($this->joins AS $join)
			{
				$this->db->join($join[0], $join[1], $join[2]);
			}
		}
 
		// Group
		$this->db->group_by($this->tableName . '.' . $this->primaryKey);
 
		// Return only row count?
		if($options['num_rows'])
		{
			return $this->db->count_all_results();
		}
 
		// Execute
		$query = $this->db->get();
		$result = $query->result();
 
		// Free result
		$query->free_result();
 
		// Filter and return
		return $this->filter_result($result);
	}
 
	function get_single($where)
	{
		$result = $this->get($where, 1, 0);
		return $result['0'];
	}
 
	function get_by_id($ID = 0)
	{
		$idColumn = $this->primaryKey;
		$result = $this->get(array(
			$this->tableName . '.' . $idColumn => $ID
		), 1, 0);
		return $result['0'];
	}
 
	function save($what = array(), $ID)
	{
		$this->db->where('ID', $ID);
		$this->db->update($this->tableName, $what);
 
		return true;
	}
 
	function save_where($what = array(), $where = array())
	{
		$this->db->where($where);
		$this->db->update($this->tableName, $what);
 
		return true;
	}
 
	function insert($data = array())
	{
		$this->db->insert($this->tableName, $data); 
		return $this->get_by_id($this->db->insert_id());
	}
 
	function delete($where = array())
	{
		$this->db->where($where);
		$this->db->delete($this->tableName);
	}
}
1Whatever you do, don’t use GoDaddy

Whatever you do, don’t use GoDaddy

GoDaddy is one of the largest domain name registrars in the world and manages several million registered domains for its hundreds of thousands of customers. I’ve just come across a disturbing article which features a video showing the CEO of GoDaddy, Bob Parsons shooting and killing an elephant at close range.

I’ve used GoDaddy for domain name registration a few times over the years but I won’t ever use them again. Bob Parsons described the video as being “one of the most beneficial and rewarding things I do”. I don’t care how wealthy you are or how you think this benefits anyone (there are other ways of moving elephants away from village crops) but this is simply wrong.

So, if you’re planning on registering a domain name please do not use GoDaddy! If you have any domains currently with them I highly recommend that you move away from them immediately. As I understand it NameCheap is offering domain transfers at ‘less-than-cost’ prices of just $4.99, plus they’ll donate $1 per transfer to Save The Elephants.

Because of this I am no longer recommending GoDaddy to anyone for any of its services and will instead refer them to this thread each time their name is mentioned. If you have a web site or blog, perhaps consider writing a post similar to this one!

25EC2 Micro Instance CPU Steal

EC2 Micro Instance CPU Steal

Quite recently I decided to downgrade one of my EC2 instances from a small instance to a micro instance. On this I have about 20 sites running, the majority of which are WordPress with a few other basic web apps and some static HTML sites.

After reading around the general impression I got was that this was a bad idea. Considering the traffic these sites get (several thousand uniques and tens of thousands of visits, daily) I was a bit concerned whether or not a micro EC2 instance could handle this load.

So far, so good. I’ve been keeping a close eye on CPU usage levels as well as memory usage and although it is quite high it is handling it just fine. CPU usage quite regularly spikes to above 50% for short periods of time but the sites always remain responsive and quite snappy. Whilst monitoring the CPU I have seen usage go sky high at peak times at which point the main feature of a micro instance kicks in and you get a performance boost to handle the load.

After a few seconds though CPU steal kicks in taking around 97% of the CPU away. This means for a short period of time the sites become quite slow (less than half a minute I’d say). Considering this happens only once or twice a day (if that) I’m really not worried about it.

Micro instances are much cheaper than small instances and since I’m running non critical sites it really doesn’t matter if the sites slow down a bit for one or two minutes each day. So, if you’re looking to get started on EC2 ask yourself, do you really need a small, medium or large instance? I’m not saying you should put everything onto a micro instance, but I do suggest that you experiment a little first and test the limits. You may be surprised to find that the smaller instances can handle what you need just fine.

17Microsoft Arc Keyboard

Microsoft Arc Keyboard

microsoft arc keyboardIt’s just arrived, and this is the first time I’ve used it. Installation was quick and painless – plug in the tiny (ultra tiny) USB receiver, insert the two batteries and you’re good to go.
First thoughts, it looks fantastic! It’s so much more appealing than my previous Logitech keyboard which although it did the job it was time that I moved to a wireless one. The Microsoft Arc keyboard is considerably smaller than the typical desktop keyboard but that’s because it’s been built for portability. In fact, in the box there’s a sleeve/pouch sort-of-thing for keeping the keyboard safe whilst on the move.

The only downside I’ve come across so far, and I noticed this within seconds of turning it on is that there is no caps lock indicator which means there’s no at a glance way of immediately knowing you’ve got caps lock on or not. Bit of a pain, but not the end of the world.

So, so far I would recommend the Microsoft Arc keyboard if you’re looking to buy a new one! I’ve also ordered the Microsoft Arc mouse so that should hopefully turn up in a day or two.

10Link exchange manager

Link exchange manager

BacklinkApp.com is a powerful link exchange manager and backlink tracker which helps you make the most of the links you’re building. The service lets you track multiple web sites meaning you can quickly and easily manage all of your link exchange efforts from one place. BacklinkApp.com lets you track both incoming and outgoing links including free, reciprocal and paid links.

Go take a look and put your name down for the beta stage now!

20CodeIgniter uploads, allow any filetype

CodeIgniter uploads, allow any filetype

CodeIgniter, the brilliant PHP framework currently does not allow you to just upload any filetype using the built in upload library. Although it’s generally a bad idea to allow your users to upload any types of file there may be the occassional need to do exactly this.

The way CodeIgniter currently does it is by making you list all of the filetypes which you’d like to let the user upload. Unless you want to sit there for a while typing a very long list why not do this simple trick. This is only a temporary fix and isn’t ideal as it does involve editing the CodeIgniter libraries but it does work. This will allow you to upload any type of file using the upload library.

Simply open up ‘system/libraries/Upload.php’ and do a search for ‘function is_allowed_filetype’. That should take you to the function used to determine whether or not the file upload should be accepted.

Now all you have to do is put ‘return true’ inside that function, right at the top. You should now be able to upload literally any type of file. Be careful though! As I said just a second ago this is generally a bad idea and can open up some very serious security holes!

12Amazon EC2 Uptime

Amazon EC2 Uptime

About a month ago I made the switch to Amazon EC2 for hosting my websites (some of them at least). I’m pleased to be able to say that the uptime has been considerably better than both a shared hosting and a VPS hosting account I have with two different hosting providers.

With my shared hosting account I was seeing uptime of around 96%, my VPS slightly higher with 98%. My Amazon EC2 instance however has seen 100% uptime since it was deployed over a month ago. That’s brilliant!

On top of that I’m seeing reports of improved page loading times which means being on Amazon EC2 my sites are running that little bit faster.

Amazon EC2 performance

28AMD Eyefinity + Bad Company 2 = Awesome!

AMD Eyefinity + Bad Company 2 = Awesome!

My active DisplayPort to DVI adapter arrived today meaning I can finally take full advantage of using three monitors with a single graphics card. I’ve been using three monitors for quite a while now but the USB graphics display adapter I was using wasn’t exactly perfect.

After setting it up the first thing I just had to try is Eyefinity. Eyefinity is a way which allows you to run multiple displays from a single graphics card and then combine them all to create one large screen. This is different from simply extending your display. By extending it you’re simply given another desktop, with AMD Eyefinity however all of your monitors are combined into one single display. So, to test out this whole Eyefinity thing why not use Battlefield: Bad Company 2? That’s exactly what I did.

Battlefield: Bad Company 2 AMD Eyefinity

In all honesty it’s a bit strange to begin with. Where with just one screen your view is quite limited with three screens you can see so much more. It’s great for playing games like this because it allows you to see more to your sides meaning you’ve got a better view of where your enemies are. Yay

26Windows 7 SSD speed boost

Windows 7 SSD speed boost

Windows 7 SSD speed differenceI’ve very recently upgraded nearly my entire computer with something a bit snappier. The older one, although not really all that old wasn’t holding up too well so I thought it was about time I spent a bit of money and get it sorted. I eventually settled on an AMD Phenom X4 (that’s a quad core) processor, accomodating ASRock motherboard, a new 1GB sooper-dooper graphics card, two 500GB HDDs (I had these already), 4GB of DDR3 RAM and something which is completely new to me, a solid state hard drive.

SSD’s (Solid State Drive) are a type of hard drive, the difference though is that they are not mechanical. This means there are no disks inside the hard drive meaning no mechanical movements are required each time you need to read and/or write to/from it. I’m running Windows 7 64bit on this new system with pretty much the exact same software as I had before. In fact, everything other than the hardware is exactly the same as before I’d done the upgrade. At first I was a bit unsure about SSD’s and considering how much they cost I couldn’t make my mind up whether or not I thought it was worth it. I honestly didn’t think that it would make that much of a difference. But I was wrong. Yay

24Moo Business Cards

Moo Business Cards

Today my batch of Moo business cards arrived in the post and I couldn’t be happier. To begin with I had ordered a sample pack of 10 Moo business cards just to get an idea as to how they would turn out – after all, this was the first time I’d bought business cards online. As I’d expected they were great and so I decided to make a real order. I’ve taken a few snaps using my iPhone (iPhone 3GS, so the camera isn’t fantastic :P). Yay

Page 1 of 512345