About Jamie on Software

Jamie on Software is the online journal of web developer and writer Jamie Rumbelow.

Jamie likes books, guitars, programming, open source and food. He writes about these things too. This is where he puts the things he writes.

My Books

Tags
Tweets
Feeds
We Love
Powered by Squarespace
Tuesday
Sep112012

MY_Model 2.0.0 At A Glance

Hot off the presses is the news that version 2.0.0 of my MY_Model base model for CodeIgniter has been released. 2.0.0 brings a huge range of new features, as well as a bunch of internal code changes, that I'll go through here.

Relationships

By far the biggest addition to MY_Model is support for basic relationships. Better relationship / JOIN support has been a widly requested feature pretty much from day one; I feel like I've come up with a simple and elegant solution to the problem.

It's not particularly performant and only supports one-to-many relationships, but for the occasions when you need a really simple and speedy way of associating rows, it's perfect.

Relationships are defined in the $belongs_to and $has_many instance variables:

class Post_model extends MY_Model
{
    public $belongs_to = array( 'author' );
    public $has_many = array( 'comments' );
}

You can then use the with() scope method to add any of the defined associations to the result:

$post = $this->post_model->with('author')
                         ->with('comments')
                         ->get(1);

echo $post->author->title;
echo count($post->comments);

Under the hood, this adds a new $after_get observer that calls the related model. This means that the result is embedded in the object, but that it suffers from the n+1 problem. If performance is important, or n+1 is biting you, it's still recommended to manually write a join in a custom method.

You can also customise the name of the loaded model and used primary key. These are sensible defaults, but can be overridden, so check out the relationships section of the documentation for more on this.

Serialisation / Serialization

If you've got some arbitrary data to insert--a data matrix, for instance--that you don't wish to set up in a traditional relational format, but doesn't require a non-relational database, you can use serialisation.

MY_Model now contains two new built-in observers, serialize() and unserialize(). Simply add them in $before_create and $after_get and watch as you seamlessly pass in complex data structures with ease:

class Event_model extends MY_Model
{
    public $before_create = array( 'serialize(matrix)' );
    public $after_get = array( 'unserialize(matrix)' );
}

$this->event_model->insert(array(
    'matrix' => new RandomMatrixObject
));
get_class($this->event_model->get(1)->matrix) == 'RandomMatrixObject' // TRUE

You can pass in absolutely anything you like and it'll be serialised appropriately. Customise the serialisation behaviour of classes by using __sleep and __wakeUp.

Soft Delete

Sometimes you don't want to destroy the row in the table, just remove it from the context of the application. Soft delete comes to the rescue. Simply set $soft_delete to be TRUE and rows will magically be marked as deleted:

class Account_model extends MY_Model
{
    public $soft_delete = TRUE;
}

Protected Attributes

I've been very lazy and have been throwing data straight into most of my models from the HTML form. This is, as I'm sure you can imagine, unimaginably dangerous and rather stupid.

Not to worry! Protect those attributes you care most about and then be reckless worry-free!

class Post_model extends MY_Model
{
    public $protected_attributes = array( 'id', 'hash' );
}

$this->post_model->insert(array(
    'id' => 2,
    'hash' => 'aqe3fwrga23fw243fWE',
    'title' => 'A new post'
));

Much More

There are tonnes of other changes under the hood and new features that I've not talked about here. A few more bits I've not explained but are worth a quick mention nonetheless:

  • The removal of Composer support. I love Composer but it was causing problems inside CI and until CI starts treating Composer properly I'll leave it out.
  • Massive internal change to the way callbacks work. Might break existing code.
  • Built-in timestamps (created_at and updated_at)
  • Manual DB override
  • A bunch of bugfixes

Contributors

Getting to a powerful, stable 2.0 has been an almighty challenge, and is the summation of a lot of people's contributions and time. A massive, Eric Pickles-sized thank you to the following people (in no particular order):

Want To Contribute?

Get onto GitHub, fork away, branch, write the code and unit tests(!) and submit a pull request. It'd be awesome to get even more contributions. Together we can build a really great base model for CodeIgniter.

Thanks again to everyone who's helped out with their feedback, support and coding skillz, and get over to GitHub now and grab a copy of MY_Model 2.0.0!

Love you all. Peace out.

Tuesday
Sep042012

The CodeIgniter Handbook - Vol 2 - API Design... Now available!

I'm very happy.

A while ago, I wrote some words. I took the words and I printed them onto some dead trees and made me a book. Enough people thought that it was interesting enough to buy a copy. In order to please those people, I've written some more words. And now you can buy a dead tree with them printed on.

In today’s world the focus in web development has firmly shifted from isolated systems to interconnected networks of applications, all talking to each other in real time. CodeIgniter’s flexibility makes it very easy to create Application Programming Interfaces (APIs) and allow your applications to chat to each other.

In this book, you’ll learn the principles behind modern RESTful API design as well as a bunch of helpful implementation details, such as how to version your APIs, how to use HTTP to specify content types and how to extend and debug your APIs with useful homegrown tools. 

It's super cheap and useful, and purchasing a copy will allow me to continue contributing a tonne of free code and advice and stuff to the CodeIgniter and web communities. So, want to learn about how to build awesome APIs with CodeIgniter? Head over to the Efendi site and grab a copy today!

https://efendibooks.com/books/codeigniter-handbook/vol-2

Saturday
Sep012012

Got To Get You Into My Life

One of the most overlooked gems hidden in the treasure-trove of The Beatles' mind-numbingly incredible 1966 album Revolver is Got To Get You Into My Life. It's credited, much like most of their repertoir, to the Lennon-McCartney partnership, but it was written almost solely by McCartney.

If you're not a Beatles fan I'd still urge you to give it a listen. It's a brilliantly uplifting track and well worth the short 2 minutes, 29 seconds required to experience it.

Listen to it there and then go and buy the album if you don't already have it. It's one of their finest.

Sunday
Jun032012

Peru - May 21

Background: This month I'm in Cusco, seeing the city and volunteering at a school project for underprivileged, impoverished kids. This is an almost verbatim entry from the diary I'm keeping while I'm out here.

It’s the morning of Monday 21st May, and I feel utterly, utterly terrible.

I reel off the list of possibilities to myself. It’s not a hangover, because I didn’t drink last night. It’s got to be something dodgy that I ate recently. I can’t think of anything in particular. I’ve not eaten from the pasaje vendors in days.

I decide that it’s probably nothing and I should let it pass.

I spend the next hour running back and forth between the toilet. Okay, it’s not getting any better. Let’s go for a walk, have a drink of water and see. I walk up to the school.

It takes me twenty minutes longer than normal. I eventually get there, and crash into one of the sofas. I feel so, so ill.

Discussion with one of the other volunteers, a nurse, strikes up a scary feasibility: parasites. After ten minutes of lying in agonising pain, I make a dive for the bathroom, and proceed to throw up everywhere. Not pleasant.

Mary, the United Planet organiser, whisks me off to the hospital.

I get admitted quickly and taken up to the fifth floor. After throwing up I feel a lot better, but I still feel incredibly suspect. To my surprise, the hospital is clean and modern, and my room is comfortable. It’s not a ward; I get the entire room to myself, complete with television and coffee table. If I’m going to get a stomach infection I’m going to do it in style.

They begin to poke needles in me. They draw blood samples from three different veins and attach an intravenous drip. I don’t like needles and it hurts, but once the drip is in things are better. It’s a weird feeling. You’re distinctly aware of something flowing into your body, but you can’t feel it directly. My left arm quickly becomes cold.

I’m left overnight. A few meals, a re-run of Kubrick’s masterpiece, A Clockwork Orange (luckily, I carry my laptop everywhere) and a few episodes of Family Guy later, they come back. And they demand more blood. Vampires, the lot of them, I swear it.

After another day in hospital, biding time, writing my novel, watching the remains of the television and film on my hard disk, and making sporadic trips to el baño, I’m finally discharged.

I’m about to get a taxi back, but the hospital deem it appropriate to send me into town in the ambulance. I get into the cab and the driver speeds through Cusco traffic, sirens blaring. A very entertaining ride home.

I’m still not sure quite what the problem was. A stomach infection, or a parasite. Either way, I spend three days feeling like an absolute mess. I take it easy and sit in cafés, taking my antibiotics, not paying much attention to the world.

By Friday I feel human again.

An interesting week, to say the least.

Tuesday
May222012

Peru - May 16

Background: This month I'm in Cusco, seeing the city and volunteering at a school project for underprivileged, impoverished kids. This is an almost verbatim entry from the diary I'm keeping while I'm out here.

I wake up at 5:15 this morning, shower, get dressed and walk up to Recoleta where Katrina is staying. The lady at the travel agency (a massive Pink Floyd fan, incidentally) tells me to be at Katrina’s for 6:10 to be picked up. I get there about 5:50. 6:10 rolls around and no sign of the annoying American or our escort, so I ring the doorbell. Within a minute a disgruntled Katrina pops her head out of the window. We get picked up and make our way to the bus terminal in Cusco.

The bus journey to Puno is long, but is broken up by stops along the way. We find ourselves visiting a church, a small village, a restaurant and a plateau overlooking the mountains. The views are spectacular and the sights interesting, if a little touristy.

We arrive in Puno at around 4 in the afternoon. We drop our bags off at the hotel we’re staying in, and wonder out into the town for a spot of dinner.

The next morning is another early start, and we’re on the boat with the other tourists by 9:30. Our tour guide, a Quechan bloke called Angel, has this habit of inflecting upward at the end of his sentences, like everything he’s saying is a question. It’s very annoying.

We arrive on the floating islands of Uros; an expansive, man-made structure of houses sitting on constructed islands of earth beds and reeds. The islands are extremely impressive, but very touristy. I get the impression our entire trip will be like this.

After we leave the floating islands we begin the three hour boat ride out of the bay of Puno into the main Lake Titicaca itself. We get along well with a couple from Chicago; both physiotherapy students and both delightful company.

We arrive on another island. I can’t remember it’s name exactly, but it was something like Isla Mantaña. Unfortunately, the relationship with our host family is totally disparate and connecting with them at all is an impossible task. They give us a bizarre, heavily potato based lunch.

Katrina and I trek, with the other tourists, up to the top of the island. The altitude up here is nearly 4,000m, and hiking up a steep slope is very strenuous.

Upon reaching the top, the entire purpose of our trip is clear. The view is utterly remarkable. Lake stretches out into the distance, with the silhouettes of mountains carving a dark outline into the sky, as the sun sets and casts an orange glow onto the landscape. 

The only thing more beautiful than the view are the stars that night. No electricity means no light pollution, and no light pollution means a stunning view of the night’s sky.

K and I gaze at the stars, and, exhausted, sleep.

The next morning we visit another island where we eat some fantastic trout in a restaurant with yet another brilliant vista.

We head back by boat to Puno. I get cocky - “Ahh I never get sunburnt!” - and promptly get sunburnt. Quiet coach journey home in the dead of night.

Lovely lunch with K the next day before she leaves back to New York. Leave her at her house. Back into Cusco.

What a wonderful few days.