Good Friday reflection

This is a reflection prepared for a Palm Sunday service (which happened to include the Liturgy of the Passion as well) at St Bartholomew’s Church, Cranmore.  It followed the reading of the Passion, as told by Mark.

 

You’re standing outside the tomb.  The evening has come.  The stone lies against the entrance, sealing him off from the world.  It is finished.

Grief fills your mind, as you recall in pain what you have seen and heard.  Jesus, your teacher, ridiculed and mocked.  Jesus, your leader, led like a lamb to the slaughter.  Jesus, your friend, heaped with insults, beaten, crucified.  Your heart breaks.

No surprise then that the floodgates open, and memories of other pain creeps unwanted into your mind.  Friends and family lost.  Relationships torn apart.  Belongings taken away.  Times when you too have been beaten, insulted, humiliated, exposed, abused, forgotten.  Your heart breaks.

But then, God’s heart breaks too.  The Father watched as his Son came helpless into the world, cold and naked and in need.  The Father watched as his Son was opposed by those who should have known better.  The Father watched as authorities wielded their power to twist an outcome.  The Father watched as his Son was arrested in the garden.  The Father watched as Jesus was accused of blasphemy.  The Father watched as his Son was beaten and mocked.  The Father watched as his Son was dragged through the streets with crowds jeering and pointing.  The Father watched as the nails drove through his skin.  The Father watched as Jesus died.  And did nothing to stop it.  His heart broke as he watched, knowing that it had to be done.

I wonder… what hurt most?  Jesus allowed himself to be arrested, because something else hurt more.  Jesus allowed himself to be mocked and beaten, because something else hurt more.  Jesus allowed himself to be nailed to a cross and had his very life taken from him, because something else hurt more.  As he hung on that cross, he looked out at the world, and saw… you.  He saw who you are.  He saw the mountain of sin that exists between you and the Father.  He saw that you would never attain eternal life by yourself.  He saw that unless something was done you would be permanently separated from him.  That was the pain that God could not live with.  That was the pain that made Jesus’ death worth suffering.  “God so loved the world that he gave his one and only Son, that whoever believes in him shall not perish but have eternal life”.  God loves you that much.  Jesus would rather go through all that than lose you.

So as you stand in front of that tomb, with the cold breeze beginning to chill your skin, with the feelings of pain and loss still like an open wound, with the bittersweet Palm Sunday still a poignant memory, with the promised resurrection still some way off, when all seems lost, remember this – God loves you.  That’s what it was all for.  So let’s bow before him, in submission, and adoration, and let’s love him too.

Don’t feed the pigeons

This is a short story I wrote on the way back from London.  Let me know what you think in the comments below!

 

As he stepped onto the platform the low, persistent rumble of the train was replaced by an altogether more muddled and frenetic ambiance. London. Liverpool Street station reverberated to the sound of idling machinery, countless footsteps, half-conversations and ringtones, all distorted by echoes from the previous second, or minute, or years, he could not tell which.

It was to be an unusually casual visit this time, simply passing through the capital on his way to Taunton to visit his grandmother. But thanks to an almost comedic experience trying to book his ticket online, which was punctuated by expletives of increasing volume and intensity, and nearly ending in a broken keyboard, he had ended up with nearly three hours between arriving in Liverpool Street station and leaving Paddington station. Normally he would expect to make the cross-capital trek on the underground in less than forty five minutes. But his stubbornness would not permit him to phone the train company and admit his error, so he would just have to live with it. And, after all, what’s the harm in a little more time in London?

His first objective was food. His lovingly prepared cheese and tomato sandwich, accompanied by a bag of Walker’s crisps (cheese and onion) and a supplement of tap water in a plastic Coke bottle, were on the kitchen table, enjoying an unexpected reprise. So he bought a tuna mayo sub and a bottle of actual Coke, and mentally apologised to his credit card for the inconvenience.

It was warm, for October. At least, it had been when he got onto the train at Chelmsford. London always seemed to have its own ecosystem, so it was never a guarantee that the weather would be the same half an hour away. But he would have to wait to find out for sure, because he was already descending into the bowels of the earth to board the circle line. Daylight would have to wait.

It wasn’t until shortly before the train arrived at the next station that he concluded he definitely was on the wrong train. He had meant to go anti-clockwise on the circle line, but this one was going clockwise. No matter. He’d get there eventually, and since he had more time than usual it wasn’t a problem anyway. In fact, now that the opportunity had presented itself, he decided to get off at Tower Hill and take a look at Tower Bridge. It would be a nice place to eat his lunch.

Signage at railway stations is big business, he mused. Posters advertised films he wasn’t interested in seeing, books he had no intention of reading, shows he didn’t have time to attend. Arrows pointed in all directions, frequently missing out the key bit of information that would have made them useful. He was informed not to leave baggage unattended, to mind the gap, and not to feed the pigeons. Most of them he simply ignored.

Tower bridge was only fairly impressive. He hadn’t actually seen it since he was a child. Not in person, at least. It was one of those landmarks that everyone knew about, and featured in every film wishing to let its audience know it was set in England. But for all its familiarity, he had never got round to actually visiting it recently. The sun shone on it brightly, but it nevertheless wasn’t nearly as vivid or as large as he had expected. He found a wooden bench to sit on and unwrapped his sub sandwich.

Pigeons are a familiar sight in London, so it was no surprised when one landed in front of him. Vermin, he thought, you’re not getting any of my lunch. It hopped around, head bobbing mechanically back and forth as it searched the ground for sustenance. He noticed it had only one good foot, and hence the hopping; the other was shrivelled, and since the bird didn’t appear to be putting any weight on it he guessed it was hurt. A fairly common injury, he presumed. Not being an ‘animal person’, as he put it, his heart strings rarely sang at the plight of creatures stupid enough to get themselves hurt. But this one was looking at him with such pleading in its eyes that even he felt sorry for it.

Thinking back, he’d never noticed birds being able to convey emotion before. Their eyes were always completely open, their face set. But this one definitely looked at him, so he thought, with a sense of yearning, longing, almost desperation. He stopped, mid-chew, and the two of them stared into each other’s eyes for a moment. He broke off a corner of his bread, and tossed it onto the pavement.

As he waited on the platform to catch the next circle line train, he noticed he was being watched. On the opposite platform stood a man, propped up against the wall, looking directly at him. There’s an unwritten rule, which somehow feels as if it should outdate the underground itself, that you never make eye contact on the tube. He found it quite unnerving seeing someone blatantly flaunting the tradition. He tried not to return the gaze, but curiosity is a powerful adversary. He looked at the floor, at the posters he had previously disregarded, at the hopping pigeon that had landed near him, at his watch, at the wall, at anything other than the man he could see was still watching him. Thankfully his train arrived, blocking the view, and he got on. He found a seat with his back to the other platform, so as to be sure not to see the man again.

With that unpleasantness behind him, he checked his watch. There was still plenty of time. He resolved to get off again at St James’s Park and have a wander, to make the most of the good weather. He was looking at the signs on the wall to make sure he found the exit, so didn’t see what was waiting for him at the other end of the platform.

Up the escalators, through the gates, and out into the sunshine again. It was London, so it was noisy, and you couldn’t exactly call it fresh air, but it was pleasant enough given that it should have been Autumn. He found his way into the park and reduced his pace to an amble. There was no need to rush, there was plenty of time.

He naturally expected the bird to move out of his way as he approached. Having nearly tripped over it, he wondered whether it was blind. It certainly had a damaged foot, like the other one he’d seen. Or was it two? He couldn’t remember. And he was distracted from trying to remember, because the bird definitely was looking at him, and clearly not blind. In fact, he could have sworn that the bird was smiling at him. Not in a friendly way, but with what he could only describe as a sense of morbid satisfaction. It was uncanny.

“So,” said a voice behind him, “you fed my pigeon, eh?”

He turned to find himself face to face with the man from the other platform, the one he had left behind at Tower Hill station. He looked more shabby close up. His waxy trench coat was stained, his hair was unbrushed and looked like it had bits of dead grass in it, and his topmost jumper (he appeared to be wearing several) was peppered with small holes.

“Excuse me?” He replied as courteously and confidently as he could, but wasn’t able to completely stifle the wavering in his voice.

“My pigeon,” the man restated, in a matter-of-fact tone, pointing at the bird at his feet, “you fed it.”

“Have… Have I done something wrong?” he answered, his mind thinking back to the sign at the station.

“No, no, mate! Of course not.” The man grinned, showing yellowed teeth, and a couple of gaps. “Now tell me,” he continued, producing a notebook and pencil from an inside pocket, “what’s your name, sir?”

Being called “mate” and “sir” in the same sentence seemed a little contradictory, so he still wasn’t sure whether he should consider this man an authority to be feared, a homeless nobody to be ignored, or something else entirely.

“Uh, my name is Martin. Martin Alford.”

“Martin… Alford, right.” The man scribbled the name illegibly in his notebook. “Good. I like to keep a record of these things. You know, for posterity.”

“And, when you say ‘your’ pigeon…”

“Oh, they’re all my pigeons. All the injured ones, that is. This one here has been mine for nearly a year now.”

“Ah, I see,” Martin replied, tentatively connecting the dots as he went along, “so you look after them? Are you with the RSPCA or something?”

The man looked directly at him out of eyes that seemed older than the body they were in, slightly misty, but which seemed to pierce the soul. His mouth attempted a grin at one corner.

“No, I’m not with the RSPCA. They would put this poor creature down, on account of his foot. Got it caught in a grating last winter. Gives him terrible pain, hardly sleeps at night.”

“Then, surely it would be kinder to…”

“Kinder?” the man retorted. “Kinder to kill it? You’ve got a funny sense of kindness, mate, I’ll tell you that. No, I don’t kill them.” He leaned in closer, as a drunk will tell a ‘secret’ to a ‘friend’. “I give them life!”

Martin looked around him. There were other people passing by in the park, but none seemed even slightly aware of his conversation with the man, none taking the slightest notice of the pigeon standing at their feet, looking utterly delighted with itself.  As far as he could tell, there was no escaping this conversation.

“Look, if you’re asking for money, I’m afraid I don’t have any,” he lied, as convincingly as he could manage.

“Money’s not my currency,” the man replied, with an undertone that Martin began to fear with increasing intensity. The man seemed to tower over him in a way that he hadn’t before. “Like I said, I deal in life. I help them, those poor suffering pigeons, cos no one else will. They’re alive as much as you are, except you treat em like vermin. Not much of a life, is it? So I help them. I give them the life they deserve, after all they’ve gone through. I guess you could call me a saint, if you like, sent to help them. To give them life. In this case, yours.”

Martin gazed up at the giant of a man that stood before him, in utter terror. Like that moment immediately after a nightmare, his scream was silent. His foot throbbed with pain.

“Seems like a fair trade to me,” the man said. He turned and bowed slightly to figure next to him, who looked much like Martin had, but who now wore an expression of relief and satisfaction, almost excitement. “No need to rush, my friend, you’ve got plenty of time now.” The figure nodded in return and walked casually away. The man flipped his notebook closed.

“Don’t worry,” winked the man in the wax coat to the trembling pigeon at his feet, “Jimmy will look after you. Welcome to my park.”

Minecraft, RSI and indispensability

Minecraft

This year I finally gave in.  I’m a creative sort of person, and I love Lego, and I love computer games, and I all too easily get lost in both of those pastimes.  So for the sake of everyone around me, I avoided Minecraft.  It combines many of the things I love most, and I could just see that once I started I wouldn’t be able to put it down.

It was when I saw my 5-year-old son playing Minecraft on my brother’s iPad that I realised I had to succumb.  It was so intuitive, tapping the screen and creating a world without limits, and Samuel loved it.  So, after much discussion with my darling wife, I paid for and downloaded Minecraft onto all my mobile devices, so that my kids could play it.  It is educational, after all.  And I’d need to be able to help them, so I had to force myself to play it too.  Poor me.

I have to say, it’s brilliant.  I love the flexibility, the way it encourages exploration and creativity and imagination.  The blockiness of it reminds me of the classic computer games I grew up with, so it’s somehow familiar.  So this year some of my favourite moments have been sat on the sofa, with a child on either side, all of us playing Minecraft together.  Bliss.

RSI

Well, it was bliss, until one evening when my thumb and wrist started aching.  That particular evening I had only been playing for about 45 minutes, but clearly it was enough.  The pain slowly spread up my forearm.  Stupid Minecraft.  I expect my general lifestyle probably contributed – I spend my working days frantically programming, and my weekends frantically strumming guitar strings, with the occasional bit of Lego in between, so my hands don’t exactly get much opportunity to rest.  But I’m going to blame Minecraft.

As the days and weeks rolled by, the pain didn’t go away.  I found myself unable to play musical instruments, and even typing and generally using a computer became a painful experience.  I tentatively self-diagnosed RSI (Repetitive Strain Injury), and bought myself a couple of wrist braces online (because at the time both wrists were suffering).  Rest, I decided was the best thing to do.

I did have a slight incident with Deep Heat, however.  You may have come across this product before – it’s meant to gently warm the muscles to relieve pain and help recovery.  I happened to have a spray version that I had bought a year or two ago when I strained my toe, and I figured it would work on my aching arms too.  So I sprayed it on.  And watched as both arms turned red and puffy and stung like crazy.  I bathed my arms in cold water, and after a couple of hours they began to return to normal.  A bit of a scare, I can tell you, especially because I was home alone looking after the kids with no transport.

Anyway, this week I finally got round to seeing a GP about it.  I described the symptoms, he pulled my wrists around a bit, and he prescribed me some anti-inflammatory pills and some hand exercises.  He ruled out Carpel Tunnel Syndrome (phew!), but didn’t think it was technically RSI; he thinks it’s probably just a muscle inflammation in the arm.  Personally, I still think there’s more too it, because it seems rooted in what I’m doing with my thumb, more than the arm itself.  Time will tell.

Indispensability

Last night my vicar prayed for me.  He prayed that if there was a lesson to be learned in this, that I would learn it quickly and then return to full health, and if there wasn’t a lesson to be learned that God would heal it immediately.  I’m deeply grateful to him for that prayer, because it got me thinking.  I wasn’t healed.  Others have prayed for healing recently too, and I wasn’t healed instantly then either.  So perhaps there is something for me to learn first.

At work, I am the only web developer.  If I’m not working, stuff doesn’t happen.  I’m indispensable.  Losing full use of one of my hands would cause inconvenience (and potentially worse) for the business.  At church, I’m the only guitarist, one of only three worship leaders (and the only one of the three that plays an instrument).  If I’m unable to play, it means all our music has to be played by one pianist, who is no longer allowed a week off.  I’m indispensable there too.

And that, perhaps, is where the lesson must be learnt.  I see myself as indispensable because I haven’t built up others to support me.  Work relies on me to be awesome, but there’s no one to share the awesomeness with, and no safety net in case I’m less than awesome.  Similarly, at church everyone relies on me to lead worship and play in the band, and there is no contingency if I can’t.  Maybe a lesson to be learnt here is to be more humble, and to actively bring others in to support me, maybe even replace me in the longer-term.  Nowhere should be so fragile that the loss of one person is crippling, and one person shouldn’t have that responsibility either.

What next?

I’m on a course of anti-inflammatory pills, so hopefully I’ll fully recover the use of my wrist.  And at that point I may begin playing Minecraft again, though perhaps for shorter periods.  In the meantime, I’ll need to put measures in place at work to find development agencies that can work alongside me on projects.  And at church we’ll need to put out another plea for more musicians.  And one day, just maybe, I’ll get round to forgiving Minecraft for being so addictive.

How to make an object oriented WordPress plugin

If you’re thinking of creating a WordPress plugin, whether small or large, for your own use or the whole world to benefit from, it’s important to start right.  Most of the example code on the WordPress documentation shows the functionalities in a procedural layout, because that makes it easier to explain.  But best practice is to use modern programming techniques – classes, inheritance, closures, and so on.

This tutorial will take you through the process of creating a very basic WordPress plugin, but created the right way.  This is partly intended to be a helpful reminder to me next time I’m creating a plugin, but hopefully others will find it useful too!

What we’ll be making

This plugin will provide an options screen in the WordPress back-end for the admin to specify how many things he has.  On the front-end, we’ll use a shortcode to display a form to ask visitors how many things they’ve got.  We’ll handle the form submission, store the number of things the visitor has in our database, and then use another shortcode to display how many things we all have in total.

It’s a pretty lame plugin, really.  But it will allow us to go through the process of making an options page, creating shortcodes, using templates, and handling form submissions.

Step 1: Naming conventions

An important thing to decide before you even put fingers to the keyboard is what to call your plugin.  Even if you’re the only person who will ever use it, you need to be sure that someone else isn’t using the same plugin name so that you don’t run into issues later.  A quick search in the plugin directory will answer your question.  And remember that it’s about the internal name, not the display name; you’ll see what I mean in a moment.  If you’ve ever asked yourself how many Daves you know, you’ll understand why unique naming is important.

First create a folder under /wp-content/plugins/  with the name of your plugin, for example /wp-content/plugins/md-things-plugin/ .  The folder name should be unique in the entire WordPress plugin ecosystem.  In theory I suppose you could use a random string here, but that would just look weird, so don’t do that.

Next, create a PHP file in that folder with the same unique name, in this case md-things-plugin.php .  For clarity it’s important that the names match, not because WordPress will get confused but because you might, or another developer who looks at the code.

Step 2: The class

Here’s our first bit of code, in md-things-plugin.php.

The comment block at the top is important, as that’s what will be displayed in your WordPress plugins page to tell everyone what the plugin is.  Technically the plugin name here doesn’t need to be unique, but it helps you be sure which plugin you’re activating!  You can probably work out what the other comments are about.

Next, we create the class, again using that unique name.  We wouldn’t want to run into issues where other plugins are using the same class name!  We’ll create a __construct()  function, which we’ll put stuff into later.  And then, finally, we simply use a variable to create an instance of the class.  The variable itself won’t be used directly, but it’s a way of making sure the class is run.

Step 3: Activate and deactivate

The first thing you do when you install a plugin is activate it.  Some plugin don’t need to do anything when they activate, but if yours does then you’ll need to catch that event and do something with it.  In our case, our plugin will need to set up a database table to store the number of things visitors have.

First off, we only want to listen out for activation/deactivation when we’re logged in as an administrator, so we’ll use is_admin()  to conditionally check.  And we’ll use register_activation_hook()  to listen out for the activation event.

There are a couple of bits of magic here.  First, notice the array in the register_activation_hook()  call.  In the WordPress documentation the first example (which is the one people read first) just has a string containing the name of the function, but since we’re using an object oriented approach our function is in a class, and using array(&$this,'activate')  is the way to do it.  It’ll go off and find the public function activate()  in the current class.  Neat!

In the activate()  function itself, we’re using the global $wpdb  object, which is how we safely access the database.  I won’t go into too much detail here on how to use the WordPress database, you can look that up yourself.  But what I do want to highlight is the dbDelta()  function.  That looks at the SQL code we’ve provided, and applies it to the database.  If the table doesn’t already exist, it makes it.  So when the plugin is activated, that table will be created too, assuming it wasn’t there already.

For deactivation it’s pretty much the same deal, but using register_deactivation_hook() .  It’s up to you whether you do anything with the database you created on activation – you may want to leave it all there, or truncate the data, or drop the table completely.  Up to you.

Step 4: The options page

This step is a little more messy, in my opinion, but I’ll try to make it clear what’s going on.  Once again, we’re only interested in the options page if we’re looking at the back-end of WordPress, so we’ll add our listener in there.

The first action uses the same technique used before of sending the event to a function within our class; I’ll show you what goes in there in a moment.

But you’ll notice that the second action we’re listening for doesn’t reference a class function, but uses a closure instead.  Why?  Personal preference really.  I didn’t see the point in creating a whole new function just for one line of code.  Keeping it in a closure doesn’t affect the functionality, and keeps the class tidy and easy to understand.  In this case, all we’re saying is that when the WP admin screen initialises we want to make sure there is a setting available for our options page to use.  Again, that will become clear later.

So, let’s look at the first action we set up, which listens for the admin_menu  action.  This allows us to add a menu item to the WordPress sidebar.  The function looks something like this:

You’ll need to refer to the documentation for add_management_page()  to see the full range of options available, but in this case we’re adding a menu item to the sidebar (as a subitem of ‘Tools’) that will be called “MD Things”, which will only be visible if the logged in user has permissions to manage_options  (so usually an Administrator).  It’s only one line, so why not put it in a closure like the other action?  Notice the last argument – we’re referring to $this , which wouldn’t work in the context of a closure.  That last bit is important, because that references another function in our class that actually displays the options page:

First of all it checks that we actually have permission to view the options page, and chucks us out if we haven’t.  It’s an unlikely scenario to have to cater for, but best to be safe.  Then we tell WordPress that our plugin uses an option variable, using get_option() .  And, finally, we show the options page itself.  This approach is my personal preference, and don’t feel you have to include the ‘.tpl’ bit in the filename if you prefer a different convention.  Here’s what options.tpl.php  looks like:

There are some styling conventions in WordPress, although I’ve found they’re not particularly well documented, so the best thing I can recommend is to look at the HTML of an existing plugin options page and replicate it.

But functionally, that’s it.  When you hit the submit button WordPress will automatically handle the form submission and save your data in the setting for this plugin.  You don’t need to worry about database access or parsing or anything… WordPress just works.

Something else that saves our bacon is that we’re saving all our settings as an array of values.  We register one option for the plugin via register_setting() , and we store all our settings as an array within that option, for example in the input above name="md_things_plugin[mythings]" .  The beauty of this is that if our plugin needed more settings, we simply add another element to the array, rather than having to create more options with register_setting() .  Nice and tidy.

Step 5: Asking for visitor input

We’re going to need a shortcode to display a form.  Again, the WordPress documentation would have you believe that this is done procedurally, but it doesn’t have to be.  I like to separate my functionality from my display, so I use template files to keep things tidy.

I’m using a closure again, because it’s tidy, but you could use a class function if you prefer.  All I’m doing here is including the template file, which looks something like this:

Now if we put that [md_things_form]  shortcode on a WordPress page or post somewhere, it will show our form.  When the form is submitted, it will be sent to WordPress’s internal admin-post.php  file, which we can hook into to process the form ourselves.  Here’s how we do that, again adding to the __construct()  function:

admin_post_  listens for post data sent to the admin-post.php  file, nopriv_  listens only to post requests that come through from someone who is not logged in, and md_things_visitor  is the identified we passed from the form submit button.  We can then route the request to a class function:

This inserts a new row in our database table, storing the value the visitor entered into the form.  I’m using intval()  to validate the input, but you might want to use something else depending on the format you expect.  Then it redirects back to the page we came from, as specified in the other input in the form (if anyone knows of a better way of doing this, let me know!).

As an added bonus, we can make that form template include a bit more information.  For instance, this bit of code would show the value our administrator put into the WordPress options page:

We can also create a static function in our class and reference it directly from the template:

Conclusion

Hopefully that’s given you enough to get started writing your own object oriented WordPress plugin.  If I’ve missed anything, or if you’ve spotted any mistakes, let me know in the comments below!

Confession reflection on a beach

DSCF2787

At church today we had the reading about when Jesus calmed the storm.  Following up the theme, I also read the following out as our confession reflection.  Various people said they liked it, so here it is – feel free to use in private or at your own church.

Imagine you are on a beach.

As we stroll along the beach, we see where our lives have left their imprint in the sand.  We see our footprints, showing where we’ve been, and where we have not.  We see our words written in the sand, every word.  We see our thoughts drawn out, exposed.  We see the crude walls we have built, to protect our feeble fortunes, to keep others out, to trap or ensnare.  We see the mounds of sand where we have tried to bury what we’ve done, to hide our mistakes, to cover up who we really are.

The sand feels rough under our feet, abrasive, cold.

As we look out to sea, the sun glitters off the waves, from the horizon all the way to the shore.  Its beauty transfixes us, constantly changing yet unchangingly constant.  A word drifts across the breeze, a smell in our nostrils, and we notice the tide coming in.  Wave after wave reaches across the beach, and slowly but surely embraces every part of it.  Our footprints are washed away.  Our words are forgotten.  Our thoughts are cleansed.  Our walls are dissolved away.  Our secrets are uncovered and cleansed in the water.  Every part of our lives is cleaned, renewed, forgiven.  As the tide recedes, our old lives are washed away with it, leaving a smooth, unblemished beach.

The sand feels soft under our feet, comforting, refreshing.

If you found it useful, do let me know by commenting below!

Controller routes in Silex

I’ve been using Laravel 4 for a while now, and occasionally Kohana too, but in my current project I’m trying out Silex.  It’s a micro-framework, which means it only gives you the bare-bones rather than bucketloads of features, but that keeps it lightweight and gives the developer a sense that they’ve actually achieved something rather than just plugging pre-made boxes together!

One of the features I was quite comfortable and familiar with was the MVC approach of having routes and controllers.  Silex, being a micro-framework intended primarily to allow an entire app to exist in one index.php file, didn’t at first seem able to do this.  However, after a little hunting around I found it was possible, and I’d like to share it here for my own reference as much as anyone else’s.

Starting point

For reference, I’m using Silex 1.2 on PHP 5.4, and I have Composer installed on my test environment.  YMMV.

Let’s assume the following directory structure:

  • root
    • public
      • index.php
    • vendor
      • autoload.php
    • composer.json

All of Silex and the Symfony libraries are in vendor, and our app currently exists just in index.php.  For the sake of demonstration we’ll use some very basic code that looks like this:

In simple terms, this sets up Silex, sets two routes, and runs.  Simple enough.  But the functionality and their associated routes are all in closures, and for a larger app this could easily get out of control.

Implementing ControllerProviderInterface

Silex includes a nice interface called  ControllerProviderInterface  which can help us out.  It requires the following to exist:

Basically, unless you have that  connect()  function and return the right thing, your class doesn’t implement the interface properly.  That’s not a bad thing though, because the  connect()  function is where all the magic happens.

Namespace

First, let’s set up a namespace so we don’t run into other people’s code.  Open up composer.json and add your namespace:

I’m calling our namespace “MyApp” for the sake of demonstration.  Save the file and update with Composer:

Class

Next, we need to create the class file we’ve just referenced.  It’s important that what we specified in composer.json actually matches our files, so pay attention, otherwise you’ll get files not being found at runtime.

We’ve told composer that our MyApp namespace can be found in /src/MyApp, so that’s where we create our class file, for demonstration purposes called MyClassController.php.

  • root
    • public
      • index.php
    • vendor
      • autoload.php
    • src
      • MyApp
        • MyClassController.php
    • composer.json

The directory needs to match what we specified in composer.json, and it’s good practice to give it the same name as our actual namespace too.

Now we can create our MyClassController.php class:

It doesn’t do anything yet, but we’ll flesh it out in a moment.  What we’ve done here is specified our namespace, made sure we can access the right components, and implemented the interface.  Now comes the fun part.

Defining routes

We’ve created a function in our class called  home() , and told the controller to route GET requests to that function.  Make sure you correctly specify the namespace and class name too.  I won’t bore you with the details of why this works (read the documentation for that), but it does.  At least, it will do once we update our index.php file to use it properly…

Mounting

So instead of defining our routes in index.php, we now let the class handle the routes itself, keeping index.php clean and succinct and allowing for more complex functionality to be extracted into separate files as needed.

Result

Putting all this together, we have the following complete files:

Now (hopefully), we’ve got exactly the same functionality we had at the start, except that it’s much more organised and arguably more powerful.

Enjoy!

The problem of excellence

I have been programming since I was 11.  I started with QBASIC, dabbled with Visual Basic, learnt Java at university, and eventually made a career for myself using a combination of HTML, CSS, PHP and MySQL.  With 21 years experience of staring at code, and a keen interest in learning new techniques and technologies, I’d consider myself fairly competent as a developer.  Competent, yes, but not confident.  You see, I have a constant internal battle raging between my ego and my humility.

This may well be a common problem for developers, who are typically introverted and occasionally socially inept*.  We strive to be the best we can be, but persuading other people to recognise our talents is difficult, and isn’t helped by our inability to articulate how good we are.

For me, I will admit that it is an ongoing struggle.  On the one hand, I know that with my years of experience I know what I’m talking about (most of the time).  I’m committed to quality, I’m excited by elegance, and I get a warm glow when I make something that works really well.  Most of the time, though, no one ever sees my excitement and satisfaction, because I’m staring emotionless at my computer screen(s) engrossed in my code, and only a truly revelatory experience teases the slightest hint of outward expression out of me.  It’s only at those exceptional times that my colleagues really notice that I’m enjoying being excellent at my job.  But even then, because it’s a world they have no knowledge or understand of, they often dismiss it as “geeking out” and rarely appreciate the awesomeness of what I’ve just done.

Actually interacting with people sometimes provides opportunities to showcase my brilliance.  For example, someone may have a problem getting something to work, and because of my years of experiencing just using computers I’m usually able to intuitively figure out the solution even if I’ve never done it before.  They’ll thank me and tell me I’m a genius.  And that’s when my humility kicks in.  You see, I know that what I’ve just done isn’t even remotely clever, and didn’t require any training, because it was just a case of pressing the right buttons.  In my own mind, it wasn’t clever, and I’m certainly not a genius.  And without really thinking about it, I dismiss my colleagues’ praise as misplaced, and mentally bring myself down a notch rather than feeling good about being able to help them.

I’ve noticed that this even happens with my development work, which is more worrying.  I work in a department that is responsible for looking after our internet presence, and I’m the only developer in the seven-strong team.  When we’re asked to make a new website or service or something, I’m the one that does the complicated development and actually makes it.  But when we showcase it to others in the business, or even externally, it’s the ‘team’ who have created it, not me.  I don’t take the credit for my own work, because I want to be a team player and build up the team as a whole.  “We” have made this awesome thing.  “We” have delivered an amazing result.  My own contribution is hidden, and unimportant.

My ego wants to tell people how great I am, because my ego knows I’m awesome at what I do.  By my humility smothers my ego so that no one sees it.  And – which is worse – I stop seeing it myself.

So how does one manage to be excellent without being egotistic?  How do you balance being a ‘team player’ against demonstrating your own skills and abilities?  Is it possible to embrace your ego AND be humble at the same time?

Right now, I don’t have a clear-cut answer to this problem.  I would love to hear from others, whether developers or otherwise, about how you have approached this problem.  Leave your comments below, and perhaps together we can help each other be confident in our excellence!

 

 

* Feel free to disagree with my on my perception of the average level of social ineptitude of developers as a whole.  And please don’t take offence if you happen to be a genuinely outgoing and socially ‘ept’ developer.

The car I didn’t buy

corsa

Looks pretty good here, right?

I’m in the market for a second car at the moment.  A classic Mini would be my preference, but that’s out of my price range at the moment, and after a lot of research I’m more or less settled on a Corsa 1.2 SXi.  I won’t bore you with the logic that’s led me to that particular choice.  Feel free to comment with your opinions anyway.

Anyway, today I went to see a Corsa that looked like it might be good, at a garage in Frome.  It turned out to be something of a disappointment.

According to their website they opened at 9am, so I rang at 9:15.  I’m pretty sure I woke the guy up.  He muttered various responses, some of which I had to ask him to repeat, but I eventually ascertained that the Corsa in question was still for sale, but wasn’t at his Frome branch because all his stock was in Radstock on Saturdays.  He gave me a postcode.

When I arrived at the postcode I found a garage, but with a completely different name, and no Corsa on the forecourt.  Confused, I gave the guy another call.  Apparently he was “round the back”.  Amid mounting concerns, I eventually found his ‘garage’ – a scruffy plot of untarmacked road with no signage and no office.  There were about 20 cars parked in the middle, right where the rain had collected in a large puddle, meaning that the majority of the cars were inaccessible.  The Corsa was right in the middle

Yep, that's the Corsa in the middle.

Yep, that’s the Corsa in the middle.

.  He apologised a bit and said that his wife was driving down with a pair of wellies.  So I waited for about 15 minutes in the cold and wind.  This had better be worth it.

It wasn’t.  Once the car had been extracted and driven to a dry part of the wasteland, I had a good look round.  This is a quick summary of what I found:

  • There was a hefty scratch, on the front wing, although it was plastic underneath so it wouldn’t rust.
  • The back of both wing mirrors were slightly scratched.
  • The trim along one side was falling off.
  • There was a nasty rusting scratch on the bootlid.
  • One of the rear light clusters was loose.
  • There was a nasty rusting scratch on the rear quarter above the window.
  • The alloy wheels were very scratched.
  • The strut for holding the bonnet up was missing its clip, so you just lay it down somewhere in the engine bay and hope it stays put.
  • The backs of the rear seats were scratched and rusting.
  • There was no spare wheel.
  • The passenger side electric window wouldn’t go all the way up without some manhandling.
  • The button that controlled the electric wing mirror position was missing.
  • Both buttons on the key fob were missing, revealing the circuit board underneath.
  • The top of the steering wheel was worn away.

In fairness, there were a few positives too:

  • The roof seemed to be complete.
  • The engine sounded in good condition.
  • The gearbox worked.

It may not surprise you to learn that I did not buy this particular car.  I’ll keep looking.

Christmas just wouldn’t be Christmas without music

There are many components to what we might call “the Christmas atmosphere”, depending on your particular preferences.  Things like satsumas, roasted chestnuts, tinsel adorning everything conceivably adornable*, flashing lights, mince pies, mulled wine, and so on.  But there is one thing that trumps them all for getting us in the Christmas mood – music.

It’s played in shops from mid-November onwards (if you’re lucky).  It’s sung by church choirs.  It’s sung by enthusiastic (if less skilled) pub goers.  It’s played on pretty much all radio stations as soon as December arrives.  And because it’s represented in every conceivable musical style, it’s accessible to absolutely everyone.

I have my own Christmas traditions involving music.  Every year, without fail, I am compelled to create a new jazzy arrangement of a Christmas carol which, sadly, is likely only to be heard by me and the spider living inside my keyboard**.  Then there’s the Christmas jazz group at church, which plays an assortment of festive tunes between the 4pm and 6pm carol services on Christmas Eve.  And of course Christmas wouldn’t be complete without tinkling the ivories of whatever piano happens to be available when we visit various family households, frequently culminating in a duet of sorts with my brother on whatever instrument(s) happen to be at hand.

Have we missed the point, though?  Are we in danger of forgetting the wonder of Jesus’ incarnation amidst all that sound-making?  This year I worked up an interesting arrangement of ‘Silent night’ on the piano, which sounded really cool, but if I’m honest it had nothing to do with the words and even less to do with worshipping Jesus.  Last night I went to the Service of Lessons and Carols at our church, a traditional choir-led evening of music and familiar Bible readings.  The harmonies made me remember with fondness singing all those parts in the school choir, and I took pleasure in listening to the natural acoustics of the church.  But where was God?  Even in a church, in a religious service, surrounded by Christians, singing songs all about Jesus, listening to verses from the Bible about Jesus, it seems it’s possible to miss what it all means (that’s a topic for another day).

Maybe I’m making a mountain out of a mole hill.  Maybe it’s just me, and everyone else hears God loud and clear in all Christmas music.  Maybe I should take comfort that we still manage to trickle-feed theology into the masses every year, getting them to sing songs about God without them realising.  One thing’s for sure – if Christmas was totally devoid of Christmas music it would take a very long time indeed (if at all) for me to feel ‘Christmassy’.

What about you?  Do you need music to get into the Christmas mood?

 

* I’m not sure ‘adornable’ is actually a word.  Apologies.

** I’m not 100% certain there is a spider in my keyboard.  It would be cool though.

God you hear

In church this morning we used the following poem as our intercessions.  We split it between three voices (not highlighted below), and it worked really well, so I thought I’d share it here.  It’s taken from Engage Worship, so head over there for more worship resources!

God, you hear the calls,
the cries,
the voices raised,
the silent whispered prayers.
Israel, in her exile, crying out for a messiah.
Elizabeth, in her barrenness, calling out for a son.
Shepherds, in their poverty, praying for a saviour.
Mary, in her innocence, searching for a safe place to give birth.
And still today the voices cry out.
In Syria, Iraq, Afghanistan, China,
and here in the UK.
The homeless, in their vulnerability, asking for a welcome.
The rich, in their emptiness, longing for acceptance.
The lonely, in their busyness, crying for community.
The families, in their arguments, praying for peace.
God, you hear the calls,
the cries,
the voices raised,
the silent whispered prayers.
Hear our prayers today,
and help us, where we can, to be the answer to someone else’s prayer.
In Jesus’ name,
Amen.