Understanding and Utilising the Expertise in your Project

So this is a topic I thought I would touch on, having worked in lots of environments, on lots of projects, with varying different sets of priorities; I have noticed a few different things; with some very common characteristics across almost all development teams.

The first is that there is a two fold problem when it comes to expertise:

  1. Expertise is never a clear cut, black and white line, every professional, in every role, has a varied set of skills
  2. The second is often the expertise people hold is often overshadowed by personalities on projects

The downside to the second point is that one can end up being entirely neglected as an asset to their project simply because their personality is not overt or extrovert; their voice not strong enough, of their opinions not heard. This can only ever be detrimental to the project, because those skills and expertise are there for a reason.

Project Archetypes

As I say, all projects are different; however, let’s assume a large website build, with complex functionality and integrated partners. I’m making this assumption for the purposes of the most complex project and set of people and expertise possible.

So, let’s look at our archetypes – I’ve given them all abbreviations to try and make this mammoth article slightly shorter.

Please do not be offended by any of the below, these are fictional characters on a fictional project to illustrate a real world point.

The Client (TC)

  • Role: The role of the client is, on behalf of their business, to get the best possible product that fits the requirements, needs, considerations, and budget for that project
  • Strengths & Skills: Nobody knows the inner workings of the business or industry like the client
  • Weaknesses: Will not always understand the implications of their requirements or changes

The Project Manager (PM)

  • Role: To bring the whole project together, encourage collaboration, and efficiency
  • Strengths & Skills: Overall knowledge of the project, from conception to delivery and beyond
  • Weaknesses: Jack of all trades, master of none; often won’t understand the low level detail of the technical elements of a project

The Critical Third Party (CTP)

  • Role: To provide the TC a third party (this could be anything from accounting software to CRM integration)
  • Strengths & Skills: Integrating their software with development teams, understanding their product, offering, and how it adds value to TC
  • Weaknesses: Usually relatively inflexible in terms of integration and capability

The Technical Lead (TL)

  • Role: Ensure the competent and efficient technical delivery of the project (technical development, testing, and delivery)
  • Strengths & Skills: Technical information, planning, and development; and understanding of the easiest route to delivery from a technical standpoint
  • Weaknesses: Sometimes seemingly inflexible, not always empathetic

The Lead Designer (LD)

  • Role: Ensure the deliverable is aesthetically pleasing, on brand, and agreeable by TC
  • Strengths & Skills: Design, brand, understanding and communicating TC’s voice by multimedia means
  • Weaknesses: Where displaying output of integrated data, doesn’t always understand technical implications of design decisions

The UX Expert (UX)

  • Role: Optimise user experience of those using the project, usually with the aim of increasing conversions, a champion of the end user(s) and customer
  • Strengths & Skills: Understanding the impacts on the user of decisions made elsewhere in the project
  • Weaknesses: Can become frustrated at the undervalue UX often receives (and is often brought in late to the project)

The Data and CRM Expert (CRM)

  • Role: Capture as much data as possible for usage by Marketing
  • Strengths & Skills: Understands every single data capturing opportunity
  • Weaknesses: Wants to capture data at every single opportunity, often to the detriment of design and UX

The SEO Consultant (SC)

  • Role: Understand the impact of all technical changes to SEO, advise on SEO strategy
  • Strengths & Skills: Search Engine Optimisation, getting traffic to the website
  • Weaknesses: Very specific skill set, often without wider technical understanding

Collaboration without restriction

As you will have noticed from the above, there are a lot of seemingly key players in this project. Consequently, I have drawn up a couple of pointers which I feel may ease the collaborative process on a project of such scale.

Understand the goals

The project should have a single, clear cut goal. Let’s say it is an ecommerce website complete rebuild and redesign it will likely be something like “increase sales by 25%”, the rebuild having been necessitated by slow page load times due to an outdated database structure, for example.

Now everybody detailed above is going to have their own set of goals. SC will want completely SEO optimised pages, and content population. UX will want a quick route from product to checkout. CRM will want to capture as much data as physically possible. LD will want the design to be beautiful, on brand, and pride of place in his portfolio. TL will want easily changeable code, efficiency and security in their code and servers.

The trick in this stage, is to understand what everyone (not just PM and TC) want out of this project. That way we can predict bumps in the road, and we can work around them before anybody has put pen to paper, code to IDE, or design to Illustrator.

Understand the dependencies

Now we understand what everybody wants and needs, we can see what dependencies there are. Likely dependencies are front end development being blocked until design is signed off. TL is likely to block integrations and development until specifications are signed, but TL is likely to be blocked on a database front by CRM until they have decided exactly what data they want to capture.

In my experience most of this will be blocked, in the first instance, by TC and PM who will need to agree and outline finalised scopes and specifications; once these are signed off the first few parties can get started in their tasks.

Understand the phases

Now we know who is involved, what they want and need, who is blocked and what order things need to be done in. Now we need to draw a plan, the phases, and who will be involved in those phases. There is no sense in a free-for-all as work will need to be redone, and there is no sense in having every party in every meeting. The popular opinion here is that it keeps the project together, working in the right direction. My professional opinion here is that, unless broken down into phases, this is a wasteful usage of time. LD doesn’t need to be in a meeting where the sole concerns are CRM, UX, and TL are discussing how and when to capture data. PM and TC should be actively involved in every phase, however, to ensure consistency across the project.

Stick to the plan

Now we have a plan, most likely with phases, timescales, and tasks down to a granular level. This has been drawn up lovingly and attentively by PM, in conjunction with all parties. On paper it will work. It is now the job of everybody to understand it, they understand the implications of the work they’re doing; so now it’s a case of move forward and don’t look back. That’s what post-go-live is for.

Understand Perfection is a Myth

Perfection is a myth. In digital it’s just not something which is possible. Browsers and devices constantly evolve. As do user journeys and user expectations. If you aim for perfection and refuse to settle for less you will never go live.

Let’s say phase 1 was to understand data capabilities, that’s been and gone. Everything has been discussed, agreed on, and is either in progress or is complete. Don’t revisit those decisions, stick with them. The consequence is we go off plan, which will cause confusion, inefficiency and definite delay; though the cost of that delay will never be crystal clear, as we’re now off plan, and away from estimations.

How you can help the large scale projects you’re on, by following these 5 simple steps

So, from working on lots of projects, here are my top tips for working in big projects.

Step 1 – Voice Your Concerns, Reasonably

There’s always a workflow or a process to follow, if you have concerns, especially those outside of your core skills and expertise; voice them. However, be careful to voice them reasonably. Don’t be deterred if you don’t get the answer you want, but also don’t be unreasonable with your fellow collaborators; their skills are not your skills. Their understanding and expertise is not the same as yours, sometimes, you will have to be told “no”.

Step 2 – Communicate for Value

This point follows upon from something I touched upon in “Understand Perfection is a Myth” above. If you are not adding value, or are not going to add value, you shouldn’t be in the meeting. If you have nothing to say, say nothing.

This does a couple of things, in practice. Firstly it cleans the lines of communications, everybody is only speaking when they have something valuable to contribute. Secondly, it makes it more likely that you’ll be listened to when you do speak, because your track record will be of only speaking when you have a strong and/or valid point.

Step 3 – Understand the People, and the Scope of their Expertise

This is a controversial one, mostly because it assumes people know what their own expertise is. Also because it means each of us as individuals acknowledging what we don’t know. SC may know one or two bits about User Experience design, but nowhere near as much as UX does, therefore it’s not really within SC’s scope to enforce decisions upon UX. Similarly TL knows nothing of brand, so beyond technical consultation should not be enforcing their views on LD during the design phase.

Your expertise is the reason you were brought into the project. If you were brought into the project as the Technical Lead, you should only insist on enforcing your viewpoint on Technical matters, unless explicitly asked otherwise.

Now I understand that this is starting to sound very much “stay in your box”, which is absolutely not the point I am making. The point I am making is when you stop valuing the experts, they lose initiative on their own ground. What that means, for your project, is that maybe TL stops making recommendations about how to keep the page speed down, because SC has made their recommendations which have been listened to over TL (and page speed is TL’s expertise).

It means LD starts doing as he’s told because TC and PM have decided that they’d rather pixel-push the design, than let LD use his area of expertise.

From what I’ve seen, letting people overrule the experts, you end up with a bunch of people capable of making changes, whilst 1 or 2 extroverted figures dictate everything. I’m open to be correct on this, but I’ve never seen it go well.

Step 4 – Empathise & Sympathise, understand Pressure Behaviour

This is the difficult one. Everyone gets a say on everything. Now everyone has to redo all of their work. All the while PM and TC are getting very excitable about how late their project is going to be, or perhaps TC is insisting upon the deadline, which PM knows isn’t necessarily possible.

Now everybody is stressed, everybody is under pressure, and everybody’s behaviours will change. It becomes “every man for himself”, this leads to some really negative behaviours in terms of what’s best for the project.

The first, is inflexibility. “Why should I do that? I’ve done my bit!”. The second, is irritability. “Why are they changing it again? I’m tired of this now!”. The third, is disrespect “Why is UX telling me about my database design, why doesn’t he stick to wireframes!”.

None of these behaviours are important. The bit that is important is that none of them are helpful for creating the best project for TC and PM.

By the time you’ve gotten to this point, it’s too late. Unless there is essentially a blank slate to work from, starting over from the first phase again, the project is doomed to be “just good enough” to get it past PM and TC and go live. Future collaborations (v2.1) will forever be tainted by this project, relationships will be ruined beyond repair. Nobody wins.

How to say “no”

This section is really founded on the principle of understanding the expertise, and respecting it. Sometimes, you do have to say no.

Approach one – “I appreciate your opinion, but I must say from a [insert skill] standpoint, it is not the best way to proceed, because of [reason]”

This approach is asserting that you value the input of other members of the team, but this is within your skillset, and it is a bad idea, which must be justified. If you can’t justify your reasoning, are you being inflexible because you don’t like the idea of someone else contributing?

Approach two – “That’s not viable given the limitation”

This is a great idea! I love it! (Or perhaps, this is a terrible idea, but it’s not viable either way). However, we have to have this done in a week, or the budget is £Xk too small. Value the input you’ve received, but not everything we want to do, is possible. That’s the basis for this particular approach.

Approach three – “That’s not in scope right now”

This is a bit of an extension on the second approach, really. This is very neutral, it’s not a good or a bad idea (unless you want to specify) but the project relies on clearly defined scope, specification, timelines, and such. Adding new things in will always impact deliverables.

This is not the worst thing for TC or PM, it’s the best thing for your current project – which is the one you must concentrate on. Rome wasn’t built in a day, if Social Media Login is a new piece of scope, it’s a great idea, but it has to wait until the completion of this project.

Celebrating the successes

It is so important, when working on a large collaboration like this, that successes are celebrated; and that personal recognition given to the parties responsible. LD had as much to do with database design as TL had with the stunning new logo alterations.

TC and PM can always take a slice of the credit, but if they’re seen to soak up all the glory, it will never be very good for the wider team. Collaboration is about accepting and appreciating the diversity that everyone brings to the table.

This vitally includes celebrating even the small successes, and attributing that credit to where it belongs. Saying “we need a logo” and then taking credit for the new design is akin to having a photo taken with Anthony Joshua, and saying that makes you the second best boxer in the world.

Continuous Collaboration

You now have a successful project under your belts, but it’s digital; it will need revisiting. You have positive foundations to lay your new project on now. There will be a sweeter taste in the mouthes of everyone who has worked on a successful project, with respected and appreciated professionals, where collaboration was free flowing, and so was respect and consideration.

Tech Team Cancer

Hi guys

I keep promising that I will be posting frequently, and then life happens. I will continue my posts and tutorials and trying to share and disseminate things I’m learning or have learned over the course of my career.

I’m incredibly lucky, not only do I have my own experiences and exposures to draw upon when trying to make decisions, but I have a number of friends in development, from starting their careers right through to development managers and such. Of course, it would be unfair for me to take all of the credit for the things I’ve learned along the way, and at some point in the near future I might post a list of people I’ve learned from, but it will be a long list; and it would be wholly unfair for me to miss anybody crucial out of that list. It’s been a long career so far and I’ve met a lot of people.

Anyway, today I want to cover a topic that’s quite close to my heart. I received a huge compliment the other day from a long time friend of mine, Oliver Sarfas, he was saying that he has just picked up a piece of software I’d developed. Now I want to throw some context into this, I first met Oliver when I was only a couple of years into my career. We have stayed in touch the whole time, but were professionally reunited at my last role.

This particular piece of software, it’s fair to say, is quite complicated in its structure; in that very little is hardcoded anywhere. I was taking a matrix of equations and building them into a data structure, running them against years of legacy data as a rule by which to calculate some financial information. In terms of fluidity and flexibility it’s one of the most complicated bits of software I’ve built. It had a feature or two that I didn’t get to finish before leaving for my current role.

Anyway, Oliver was tasked with finishing up the project by building some of the functionality I didn’t get chance to do. He sent me an email, the long and short of this email was a thank you for writing code using industry standard techniques and leaving decent documentation. I can only presume following PSR-2, known design patterns, and decent naming conventions played some part of this.

This really conveniently brings me to the point of this post:

Tech Team Cancer

It sounds like a really horrible thing to refer to, but truthfully the things I am about to describe are cancerous. I’m not pointing at any of my previous roles here, everyone does at least one of the things on the list, some companies are better than others, but generally, these things help kill tech teams:

1. Not Leaving Documentation (Ivory Towering)

There is nothing worse than finding yourself having to work on a project you know nothing about, that has no code comments or documentation attached.

One thing I would like to say on this, however, is code comments are great tips for a developer. But code comments document that piece of code, that module, that class. They don’t document the over-arching design or principles of the piece of software.

Documentation is essential in other developer’s being able to work on your software.

2. Not Following Patterns

This is a bit of a weird one. Using known design patterns, and principles, and everything else does help your code’s maintainability. But what I really mean here is being consistent, across all of your code (really it should be across all of your team’s projects). Any convention is better than no convention.

If you have a piece of software and you name all of your classes following PSR-2 standards and your namespaces follow PSR-4, great! Get everything else consistent too, table and field names are a really common one for this.

3. Not Knowing When You’re Out Of Your Depth

This is another seriously fluid one. Any time you are out of your depth is bad. It doesn’t matter the context. Don’t fully understand the specification, don’t fully understand what they’re aiming to gain, or the use case, for this software, don’t understand the technologies you’re using. Any of these things lead you to build bad software.

What usually happens, in my experience, is that you, for want of a better phrase, blag it. Blagging, in development, is terrible. It means you don’t have a plan, if you don’t have a plan how can you have a coherent software design and accompanying principles?

If you have none of those things you’re destined to end up with spaghetti code, indecipherable nonsense and, as you learn more about what you’re supposed to be doing, horrendous shoe-horning to make functionality work.

The big problem with this one is that if you fall foul of it you will definitely fall foul of the other points here as well.

4. Bad Commit Messages

We’ve all been in that position where we’re asked to fix a bug on an existing piece of software. Fair enough. And then we look at the code, and all we can say or think (depending on your personality) is “Oh for ****s sake, what the **** was that **** thinking?! Seriously why the **** would you do that?” and this usually lasts for a few hours, before resigning yourself to shoe-horning in the resolution or stating it has to be rebuilt.

This is where a decent commit message goes a long way, and a code comment. If I have to do something a bit nasty, dirty or something that would get my immortal soul cussed out once I’ve left the office, I leave a code comment and a commit message; keeping professional but saying something like “This is a workaround for requirement X which was introduced after the original specification; if you change it Y will happen and you will also need to check Z” – because that’s the kind of information I would like to find if I were inheriting the maintenance of that code.

A good commit message is the difference between “Why the hell did you every hire X? He didn’t know what he was doing!” to “Ah, right. I see why he did that, it sucks, but I get it”.

5. Relying on Tribal Knowledge

This one is so much more dangerous than it sounds. When you build something, or when you fix an issue. This one isn’t just for developers either, testers, client facing staff and project staff are all guilty of this (usually). If you know something about a project or a piece of infrastructure it really does need to be written somewhere.

Take this real world example. I was working on a large and complex project which was business critical for the company that I was working for at the time. We were nearing the end. Luckily I keep documentation and code comments pretty up to date and always communicate how I’m working on. Unfortunately one Friday afternoon, I’m on my way home from work, all is good, we’re ahead of schedule and everything is great with regards to the project.

Then I’m on my way home, hit oil and come off of my motorbike. I go rolling up the A14 in Cambridgeshire, breaking and dislocating my shoulder and snapping my thumb. That’s me unable to drive for about 12 weeks in total. I was really lucky, firstly I didn’t die. Secondly, I used to work part remotely, so was able, within a couple of days and a makeshift injury-friendly work space, to get working again.

Imagine if it were worse, or if I couldn’t have worked remotely. The company I was working for would’ve been right up the creek without a paddle.

In Summary

To summarise this article. The main problems any development team, whether growing or shrinking, young or old, is information and sharing it.

Whether you’re sharing it through documentation, code comments and git commit messages. Or however you’re sharing it. Whether than information is software design, client facing, client requirement, anything at all. If ever there is a piece of information that you, and you alone, have you need to find a way to share it; otherwise you really are asking for something to go wrong with no conceivable disaster recovery available.

Tips for commercial WordPress, and open source, development

Hi everyone

So I’ve been using content management systems on and off for the best part of 10 years. From the by-gone days of PHP Nuke and when content management systems like PHP Fusion were all the rage. To using more modern, and definitely more widely adopted systems like Joomla and, of course, WordPress; and just to throw other open source stuff into the mix, platforms like Moodle.

Now I’ve returned to using WordPress on a daily basis, but from a different perspective; I don’t do too much development on WordPress personally; my skill set generally lies in building things on frameworks such as CodeIgniter and Laravel, if not bespoke. But I do use WordPress to the extent of managing multisite installations, managing production stability and servers, as well as deployments and migrations.

Having been in the unique position to pick up some legacy code in my time, and seen what does and does not make a WordPress site easy to work on, manage and maintain; I thought I would put together some tips for building WordPress sites, and functionality, which will stand the test of time.

1. Never modify the core

This is a deadly serious one. No matter what you’re working on it should have a specific way of extending functionality, whether through plugins and themes, extensions or a specific namespace where modifications should be added, never, ever, ever modify the core. The same applies to the core code on a plugin.

The reasons for this are really simple; you probably don’t know and understand the full architecture or what you might break by changing this, and more importantly the biggest strength of using something open source is that updates are generally frequently available. The moment you change something in the core you’re going to sabotage any upgrades; you will have to make the choice. Either update the software (absolutely critical) and lose your changes, or don’t update the software and risk leaving bugs, security vulnerabilities, and all kinds of other stuff in there. Not a good position to be in.

2. Choose the right one

WordPress is the most widely adopted content management system in the world. Impressive, right? And technically, yes, anything can be built on it. In the same way any system can be built using .txt files for data storage. It can be done, but that doesn’t mean it should be.

I’ve laboured this point a few times in a few articles and things, but a good developer will know the tools available to them and choose the best one for the job. It is worth spending six months for a content management system and blogging platform, that does exactly the same as WordPress? Of course not. Is it a good idea to build a secure intranet containing sensitive data about national security on WordPress? Of course not. It’s about knowing what’s available and making the best decision based on this.

This is a difficult one, however, as you need to choose the one that fits your needs right now, as well as being compatible with the long term visions of the site; or know from the start that a rebuild will be necessary.

3. Be wary of plugin dependencies

Why use plugin_function when cms_function does the same job, and is probably going to be better supported in the future? When installing plugins, extensions and add ons; always think about the eventualities? What if this plugin’s core is compromised and I need to disable it right now; what will break? What if the plugin stops being supported? How tied into using it am I right now? If you’re managing lots of websites, especially; be wary of the headache you’re going to have if you’re relying too heavily on too many plugins.

If you notice yourself using plugin X on every site you build, or relying on it super heavily, it might be worth doing one of a few things. Either building your own replacement, so you’re in control of the core. Or perhaps wrapping it in your own functionality, so if you want to swap it out, you can. Using a technique called Facading can help with this, hiding plugin functionality behind you facade means you can swap what’s behind the facade out if you need to.

Really the point here is don’t install things willy nilly, think about the dependency you’re creating on this plugin for your website, and how much of a pain it’s going to be if you want to remove it.

4. Always check the source

Depending on the project and the size reading the source code line for line probably isn’t going to be efficient; so that’s not what I’m suggesting here. By source I mean the author, the factory, the company; wherever it comes from. Make sure they’re trusted, WordPress, for example, examines all of the plugins and themes submitted to their public repositories and they’re pretty stringent on their standards, as well as ensuring they’re safe (from a security standpoint).

Most mainstream CMS have white hat security scanning tools that will uncover most, if not all, known security flaws and vulnerabilities. Running these can only be a good thing, as long as you act on the results you get.

5. Don’t be afraid to code things from scratch

There might not be a plugin which does what you want, or doesn’t do exactly what you want. You have 10 requirements from your client. Plugin X fulfils 9 of them. Do not try and hack it to fulfil the 10th, it will only go badly; honestly, I’ve been there and done it a bunch of times.

Just because you usually use X plugin and Y CMS, doesn’t mean you have to this time. Some things are best built from scratch, whether the whole site/software, or a specific functionality. Sometimes the best option is to get stuck in with coding the thing you want. You’d be surprised at how quick this can sometimes be. And just because your CMS offers a specific functionality doesn’t mean you have to use it. WordPress Custom Post Types are a beautiful example of this, as well as their taxonomies. These are both beautiful pieces of functionality; but they’re not the best way to store bespoke data, for example. They exist for a range of things, but primarily to give you a way to show bespoke content, like recipes, and linking them together in a specific way, dietary requirement for example. Storing anything that doesn’t fit into a custom post type and taxonomy doesn’t make sense, so don’t do it.

From procedural to object orientated, a tutorial

Hi there everyone

Something I’m often faced with, having lots of friends with varying degrees of programming experience, is how do (PHP) developers move from sub 25k roles to the higher end of the spectrum, the 35-60k developer roles.

Generally, in my experience, the are some key differences in the salary expectations and the skills you can expect for a developer demanding those salaries. These can be broadly summed up as below:

  • True understanding of object orientated programming
  • Knowledge and application of programming principles
  • Exposure to multiple technologies and ability to move around within them
  • Web application development vs website development (the difference between relying on browsers and being able to do things like offloading, queueing, sharding, true separation of concerns, performance optimisation, caching, all that stuff)

To this end I’ve had a decent number of developers ask me how to start working with classes, and work in an object oriented way. So I thought I would do a tutorial on this. I’m going to cover some design patterns, some PHP functionality and various other things.

This is going to be a long and wordy tutorial, but hopefully what it will do is give you some understanding in the differences between procedural and OO programming.

All code samples are available in this project on my GitHub

Step One: The Hardest Part

The first thing I am going to disclaim is simple: Please do not try to have a half procedural, half OOP project or system. It’s going to be an absolute nightmare to maintain!

Now that’s out of the way, let’s talk about some design basics. Avoid god classes! A god class is a class which has many, many responsibilities, it can do everything. In terms of a practical application of a God class think of an ecommerce system: if a single class is responsible for checking stock, adding items to your basket, emptying your basket, and the checkout process – it has far too much responsibility.

I always think it’s a good idea to follow the Single Responsibility Principle – to those new to this I simple explain it as follows:

A class should be responsible for a single job. If you can’t tell me, in a sentence, what it does; then it is almost definitely doing too much.

As such if you have a requirement for an ecommerce system as defined above, checking stock levels would be it’s own class. The point of this is so that:

  1. The class can be used throughout your project, anywhere that you need to check stock levels
  2. The class can be modified and know that all stock checking functionality happens through a single place
  3. Any business logic can be contained in a single place
  4. The class could be swapped out if needs be, again you know all functionality is encapsulated here

Encapsulation: Goes hand in hand with “DRY” (don’t repeat yourself). Basically bringing everything to do with a certain concern (i.e. stock checking) into a single place, rather than leaving it scattered throughout your code.

So you now have a basic idea of what you use a class for, and in what scenarios you would create a new class – basically, any time you need to get something done.

Now working with objects, as opposed to working with a bunch of variables, has some real perks.

NB: Throughout this article I am going to refer to “classes” and “objects”. For all intents and purposes a class is defined, an object is instantiated. Therefore my User class, once it physically exists, becomes an object, until that point it is a class.

If I have an “Order” object rather than a whole heap of variables or a massive multi-dimensional array, I can put functionality in there which I need, I can do decisions and logic based on information contained within that order. What you’re doing is neatly organising everything into it’s own compartments within your code.

The user may be hitting a button to “add to cart”, but in practice you might be doing all kinds of things; checking the stock level, applying voucher codes, modifying the stock level, calculating the value of the cart so far, all sorts. So this separation becomes invaluable.

However, the point of this part of the article is simple. It’s going to be really difficult to follow, and make almost no sense, to have a bunch of objects floating around a procedural execution. The reason for this is, again, simple; if you have some stuff procedural, and some wrapped in classes and objects; how the heck could I possibly know where to look?

Learning Point Two: Using and understanding the syntax

In this point we’re going to cover some basic concepts:

  1. Inheritance – abstracting and extending classes
  2. Interfaces – implementation and usages
  3. Properties, Methods, Privacy and Scope

Firstly, one of the beautiful things about classes is inheritance. Let’s take a basic example of a User. A User might be a Guest, a Member, a Moderator and an Administrator; but they almost definitely share a bunch of common functionalities, like having a user ID for example (though a guest’s would be 0 or null). You don’t want to have to write a whole heap of code to get the user ID a bunch of times, when it’s the same functionality. You want all of your different types of users to share this functionality, this is where inheritance comes in.

Inheritance

<?php

abstract class User
{
    protected $userId = 0;
    protected $isLoggedIn = true;
    protected $isStaff = false;
    public function getUserId()
    {
        return $this->userId;
    }
    public function isLoggedIn()
    {
        return $this->isLoggedIn;
    }
}

class Guest extends User
{
    protected $isLoggedIn = false;
}

class Member extends User{}

class Moderator extends Member
{
    protected $isStaff = true;
    public function hasPermission($permission)
    {
        // Some logic here and return TRUE or FALSE
    }
}

class Administrator extends Moderator
{
    public function hasPermission($permission)
    {
        return true; // Administrators can do anything
    }
}

See in GitHub

The handy thing about this is that everyone is a User. So if ever I try to manage some dependency and state that a User is required as an object, I can do this really easily, because everything extends off of User, or one of its derivatives.

Also everyone from Guest to Administrator has a getUserId method, which is quite handy and an isLoggedIn method, so it doesn’t matter if my factory returns me a Guest or an Administrator, the functionality is going to work.

Just to clarify some bits here. Guest::isLoggedIn is false, but Member::isLoggedIn (and everyone who extends Member, or Moderator) returns true. Moderator::isStaff returns true as does Administrator::isStaff (because of the inheritance).

Site note: You could never do: $user = new User(); Because User is defined as an abstract class, as such you could do $administrator = new Administrator(); (or any of the other classes)

Interfaces

An interface is, the best way I’ve heard it described, is the difference between plugging a socket into the wall, vs having to wire in your lamp by hand. You can define an interface on an object, to ensure it conforms to certain standards, basic example now of an Emailable interface.

This interface ensures that the entity, whatever it is (User, Customer, Employee, Organisation, Website) can be emailed, by specifying it must have some methods available to it.

In this example we can make anything we want emailable, by simply adding the methods defined and stating that this class implements the interface – now we can send an email to the fridge if we wish, as long as it can define those methods!

<?php

interface Emailable
{
    public function getRecipientName();
    public function getEmailAddress();
    public function acceptsHtmlEmail();
}

class Client implements Emailable
{
    public function getRecipientName()
    {
        return 'Very Important Company Plc';
    }
    public function getEmailAddress()
    {
        return 'someone.somewhere@clientwebsite.com';
    }
    public function acceptsHtmlEmail()
    {
        return true;
    }
}

class Employee implements Emailable
{
    public function getRecipientName()
    {
        return 'John Doe';
    }
    public function getEmailAddress()
    {
        return 'john.doe@ourcorporateemail.com';
    }
    public function acceptsHtmlEmail()
    {
        return false;
    }
}

Sample on GitHub

Implementing an interface: Simply means that we have defined an interface, and the class which implements that interface conforms to it. Then if we define Emailable as a type hint, PHP will force not only that the class implementing the interface, but also that any object parsed into an Emailable type hinted parameter conforms. Otherwise it’ll throw a hissy fit and not work

Scope!

The big one that catches a lot of new-to-OOP developers out is variable and method scope. So here is a quick and simple one:

  1. Public – these methods and properties can be accessed (as long as the object is instantiated) from anywhere that has access to the object
  2. Protected – these methods and properties can be accessed within this object (or derivatives)
  3. Private – These can only be accessed specifically within this class
  4. Static – These can be accessed from the class itself, without needing the instantiation of an object
  5. Constants – As in PHP itself, these never change

That’s the long and short of it. Word of warning! Always assume your code is going to be copied, recreated and used throughout a system and if it is open source by anyone anywhere in any way they feel like it. So be very careful what you expose as public, once it’s public you have to assume code is relying on it, and as such ensure you are backward compatible – what I’m saying is it is easier to change $myProperty and myMethod to be public later, if they were protected before, than to change them from public to protected – because who knows what you might break!

Accessing properties can be done as follows:

Please do not try to run this code, it won’t work 🙂

<?php

class Scope
{

    // I will never change
    const GITHUBURL = 'https://github.com/johnothecoder';

    // I can be called from the class, without instantiation, and can be shared across multiple instances
    public static $fullName = 'Matt Johnson';

    // I can be access from anywhere the object exists
    public $alias = 'JohnoTheCoder';

    // I can only be accessed from within Scope or a class which extends Scope
    protected $name = 'Matt Johnson';

    // I can be called from anywhere
    public function getAlias()
    {
        return $this->alias;
    }

    // I can be only be called within Scope (or classes which extend scope)
    protected function getName()
    {
        return $this->name;
    }

}

// Executing some code

echo Scope::GITHUBURL;
echo Scope::$fullName;

$scope = new Scope();
echo $scope->alias;
echo $scope->getAlias();

// But I can't do this
echo $scope->name;
// Or this
echo $scope->getName();

As always, sample available on GitHub

I can’t really talk you through the full spec of this one, as there’s not much to talk through, really it’s just a way of showing you what can and can’t be done within the scopes of an object.


Hopefully this article has been of some use to those of you looking to get into the big wide world of object orientated programming with PHP. Next time I will be covering how to use Dependency Injection, the Factory and Service locator pattern and polymorphism to your advantage 🙂

Thanks for reading!

About Facading and Dependency Injection

Good evening everyone.

I’ve been meaning to write a post about this for a little while, it’s a common discussion point within developers working on enterprise level software. The argument regarding dependency injection vs. facades; how they’re applied and how they relate to most software systems you work with.

The first point I would like to make on this particular topic is that they are both useful, they both have their place.

For those of you who are not exactly aware of what these concepts are I have broken it down a little bit below; but if you’re not comfortable or familiar with the topic it probably is worth doing some research on before you make your mind up.

In essence, dependency injection is where you declare your class usages in a single place as a dependency, those dependencies are injected into where they are used. The concept behind this is that should you wish to swap out your dependency it should be easy. Take the following example;

I have a class named PermissionChecker. This class is used throughout many Controllers in an MVC framework. Whenever I want to check if someone has a permission I simply call upon functionality within the permission checker, which returns me a true or false.

The basic problem here is when I want to change the PermissionChecker, which contains all of my permission-based logic, it is painful, because I have to go through and replace or remove every instance of the PermissionChecker and hope that it doesn’t break anything, and I test everything heavily.

This is where Dependency Injection (DI) comes in. I create an instance of my PermissionChecker (PC) within the DI container. There are various open source DI solutions out there from Pimple to the DependencyInjector by Symfony. Anyway, the long and short of it is that the declaration of the usage of PC is in a single place, so should I wish to change it for SupremePermissionChecker (SPC) then it is easy and done in a single place, assuming the interfaces through which it is accessed remain the same.

This is the perfect solution to an age old problem!

But beware! There is an issue with DI, in my experience, and that is that either you become so dependent on it that it becomes difficult to utilise functionality and you end up writing lots of code which, in practicality, does very little. Or potentially you can end up over injecting, some parts of your system will be tightly coupled to one another by design, the issue with DI here simply compounds this issue, because the tightly coupling in a lot of days makes the DI redundant; as you couldn’t swap out the dependency even if you wanted to.

Now please don’t, for a second, think that I am slating dependency injection, because I’m really not. I think it is a very useful tool, it’s not my tool of choice but it does have a lot of advantages.

Additionally; don’t think the next thing I am going to mention is mutually exclusive to Dependency Injection either, they can be used in tandem without any issues.

So a facade is where you create a class which hides more complex logic behind it. Taking the same example I might have a PermissionChecker class which facades other functionality, for example fetching a user, fetching permission records which it can cross reference against the permission we are checking into.

In essence a facade is a way of abstracting your functionality a layer further. You have your system which utilises your facade, and your facade utilises whatever it needs to.

The reason I prefer this methodology, personally, is because you end up with all of your facades talking to one another. Which makes your Controllers very readable as you end up with something not dissimilar to:

if ( $permissionChecker->hasPermission(‘make-payment’) ){

$paymentThing->makePayment( $account, $sortCode );

}

Which I feel is very “English” in that it’s quite easy to read it and understand what’s going on. Additionally the advantage, for me, is that if Developer A (DA) and Developer B (DB) are both working on functionality within the same version it is easy. DA can be modifying whatever he wants in PC whilst DB can be happily working away on changing the payment gateway PaymentThing is using, as long as the interfaces remain the same then it’s all good.

To add to the mix, remember where I said earlier the two weren’t mutually exclusive? PaymentThing and PermissionChecker could well have both been dependency injected into their current context, so they could be switched out.

My only real question there is: why? If my functionality is all hidden behind facades, which provide easy interfaces to use, if ever I want to change them or do anything with them, I do it behind the facade and I’m fine. With that in mind, does Dependency Injection become a bit overkill?

Both of these concepts, as with all concepts, methodologies and rules within web development, are designed to make maintaining my software easier, rather than having invisible dependencies and entangled tight coupling which is impossible to defuse. That’s a developer’s nightmare when someone says “can’t we just take the payment functionality from X project and put it into Y project?”.

I think we have to sometimes be careful in web development and programming in general that we’re not making more work for ourselves. If facades are working for the separation of concerns, does it matter if the dependencies are scattered through the code, because somewhere that once needed to make a payment will always need to make a payment, and if that requirement changes, the code will need to change anyway, so we cut out the bit that says make a payment. We don’t have to remove the dependency or do anything else.

When I want to include payments into a new set of functionality on the site all I have to do is utilise the use statement to bring in the Facade, which handles everything else, and use the functionality contained therein.

Maybe I am missing the point and the value. And I would rather have Dependency Injection than nothing, but I would rather have an easy-to-utilise set of Facades, than have to Dependency Inject everything I want to use, and remember to rip it out when I don’t.

I’d love to hear other developers’ opinions on this one though, as it is something of a bone of contention in the community.

Take care all!
Johno