Quick Life Hacks with the Eloquent Model

Hi folks,

It’s no secret that I love Laravel, and especially love Eloquent. This post isn’t about why various people don’t like Eloquent, etc, etc. but just some “life hacks” of working with Eloquent.

#1 – Naming Conventions

I personally like to use the following naming convention on my databases (using a forum as an example)

forums
forums_topics
forums_topics_replies

Whereas Eloquent would expect the following:

forums
forum_topics
forum_topic_replies

I personally dislike this, for no other reason than I like to be able to see what’s being owned by what at a very quick glance. Additionally, namespacing; I like to namespace my Models, at the very least into a Model namespace, but often I like to further namespace these to represent the ownership of the data; so I end up with something like (I’m using a directory structure, because PSR-4 namespaces follow this anyway)

app/
- Model/
- - Forum
- - ForumTopic
- - ForumTopicReply

My only issue with this is that the Model namespace can end up huge, and with classes with some really ridiculously long names. So I prefer to break this down like so:

app/
- Model/
- - Forum
- - Forum/
- - - Topic
- - - Topic/
- - - - Reply

I realise this begins to look like overkill, but I find it particularly useful when separating functionality by module or something like that.

The Autonaming

The above means I have two options, number one is to follow the convention to the letter. Option two is to overwrite the naming convention on a base model, from which I then extend. This base/abstract model contains the following method:

/**
 * Overwrite the autonaming conventions
 * @return string
 */
public function getTable()
{
    $class = substr(get_class($this), strlen(self::MODEL_NAMESPACE));
    $namespaces = explode('\\', $class);
    foreach($namespaces as &$namespace){
        if(substr($namespace, -1) == 'y'){
            $namespace = strtolower(substr($namespace, 0, -1) . 'ies');
        } else {
            $namespace = strtolower($namespace . 's');
        }
    }
    return implode('_', $namespaces);
}

Note: You will need to have the MODEL_NAMESPACE constant declared as well

All this does is turned app\Model\Forum\Topic into forums_topics, but it’s pretty useful

PSR-2 properties

So the other thing I find occasionally annoying is that when writing PHP my properties follow the PSR-2 naming convention (camelCaseForVariables) – but using eloquent I am forced to snake_case_columns because (understandably) this is what is in the database.

By adding the following 3 methods to your base model you can use PSR-2 compliant field names. So that created_at becomes createdAt; without having to modify the database;

/**
 * Overwrite the getter so that we can use camelCase field names
 * @param string $property
 * @return mixed
 */
public function __get($property)
{
    return parent::__get($this->convertToSnakeCase($property));
}

/**
 * Overwrite the setter so that we can use camelCase field names
 * @param string $property
 * @param mixed $value
 */
public function __set($property, $value)
{
    parent::__set($this->convertToSnakeCase($property), $value);
}
/**
 * Turn a camelCase string into snake_case
 * @param $string
 * @return mixed
 */
protected function convertToSnakeCase($string)
{
    return strtolower(preg_replace('/([a-z])([A-Z])/', '$1_$2', $string));
}

Quite simply, all these methods are doing is plugging into the original getter and setter, but first converting camelCase to snake_case – so that throughout my code I can refer to these fields in a way which is fitting with the rest of my code, which conforms to PSR-2

There you have it

A couple of very quick, but very useful, ways to extend the base Eloquent Model so that it is in better fitting with the rest of your code base and database standards (or mine, anyway)

You are the worst programmer in the world

You, yes you, are the worst programmer or web developer in the world. Without a shadow of a doubt. In someone’s opinion.

The thing about programming or building anything is that it’s almost entirely subjective. Of course there are certain things which are categorically bad like lazy developing, obvious bugs, security vulnerabilities and terrible performance (both server side and client side).

The point of this article, really, is to ask the question: Why are we, as a community, so judgemental?

There are plenty of controversial topics, when you get into web development. Factory patterns vs dependency injection vs just using classes/objects. Then there’s the design patterns, and the fads; are CMS better than bespoke applications? Well there are arguments for both. Is a factory pattern better than dependency injection; well it depends what you’re doing.

Should singletons be outlawed? Should business logic be in the Model (in an MVC system). Should a framework be used or a bespoke code base? Should functionality for a bespoke WordPress build be in the theme, or should it be wrapped up in a separate plugin? But then what about the inter-dependencies.

Even onto the microtopics. I’ve decided I want an MVC, RAD framework; if you use Laravel you’re (insert insult/compliment), but if you use Symfony you’re (insert insult/compliment); but hey if you use Zend then you must be (insert insult/compliment).

Why is this community so anti-everything-else?

We have so much more in common than we disagree on. We love to build things. We love to make them the best thing out there. We love to make people (whether end users or other developers) go “wow, that’s clever”.

My theory is, these judgements come from previous bias. You know the kind of thing “I used WordPress this one time, and it was terrible, so naturally I now hate WordPress, and anybody who advocates it” – you could swap WordPress there with anything. Dependency Injection and Containers, MVC, Procedural, OOP, MySQL vs MariaDB, Apache vs NGINX. Linux vs Windows.

Flaming ensues

So, you have a disagreement. We all have disagreements. Those of us in the web development community, however, seem to disagree fiercely with one another. I’m not entirely sure why, though I suspect it’s psychological attachment to previous judgements of the given topic of debate.

These disagreements often turn heated and invariably someone is referred to as an idiot, unprofessional, or something that otherwise challenges their experience, expertise, or intelligence. Which is just a bit harsh really.

People leave

This is the worst bit, and it doesn’t matter the context. Whether a forum, a social network, a work place, a specific team, a social group; it’s terrible. It’s horrible to think someone should feel so undervalued, or become so tired of the arguments, debates, whatever you want to call them that they lose their passion for programming.

This is particularly bad for businesses, who due to strong personalities and strong opinions, have to watch people walk out of the door because of a lack of compromise.

So what should we do?

I think we should stop, and think. Try to consider the other person’s point of view, and empathise with their opinion. Sometimes it’s a difference of opinion, sometimes someone is flat out wrong. If someone is flat out wrong, then perhaps some education is better than essentially telling them they’re stupid (I’ve seen this happen in a meeting, I felt for the guy on the receiving end of it). If it’s a difference of agreement, there’s nothing wrong with discussing opinions and maybe even agreeing to disagree.

My favourite quote, in relation to this, ironically is from Bill Nye the Science Guy; I saw a very short clip but:

Everyone you will ever meet knows something you don’t

So I think we should consider that more. Skill and knowledge can’t be easily determined by qualification or years of experience. I’ve known fresh faced junior developers on not much more than minimum wage who have been some of the most talented developers I’ve seen, simultaneously I’ve seen cozied up senior and lead developers who frankly couldn’t match up to most of the programmers on their team.

Give everyone a chance. A chance to prove they can do it. A chance to show they’re heard.

What happens if we don’t?

This is the bit I don’t like. People leave, as my point above. We’re getting more people through the doors of this industry than ever before. More people wanting to learn, wanting to know and to understand.

I love people wanting to get involved, that fresh-eyed enthusiasm is a wonderful thing. Then they go on the internet. Either publishing some code, or doing something which the community as a whole can see.

Then someone mentors them, often more than one person; in the form of comments on the commits, or discussion in their forum threads, etc. This is where the differences of opinion kicks in, the poor junior developer doesn’t know what to do. They’re torn between multiple opinions, none of which are necessarily right, but most of which are likely to be subjective.

I’ve seen this put people off of PHP altogether. Ironically they then move into other technologies, some of which the communities are even more judgemental; just not so openly hostile about it.

In someone’s opinion, you’re the worst developer going

Perhaps the particular context you’re in, your opinions are seen as the right ones. Fair enough. Why flame someone who doesn’t share them? All you do then is force everyone to stay where their views are welcome.

Every developer, every language, every framework/CMS/system has its own quirks. Probably for good reason. You can’t have everything, all of the time.

If it’s you, don’t be deterred

Just a quick note of positivity really. If it’s you being flamed on {whatever site}, don’t worry about it. Sometimes they might have valid opinions and experience (try to decipher them out of the flame). Don’t get caught up in it, don’t be put off. Keep doing what you’re doing.

It doesn’t matter if you’re a junior and have just got involved, or you’re someone whose been doing it a long time. There will always be someone, somewhere who thinks you couldn’t possibly be a worse developer.

If you’re happy with what you’re doing, you don’t have major code problems, your manager(s), colleagues, and client(s) are happy. Well, who cares what someone else says. Especially when they’re a faceless voice on the internet.

 

Quick and Easy PHP Singleton

Hi guys

A really short one today, just because someone asked me about it a couple of days ago. I also though it potentially best to avoid something as controversial as my last post about Eloquent and the Single Responsibility Principle, which caused a bit of a stir during the week.

So, you want to make sure you only ever use one specific instance of a class (maybe a DB connection) and need a quick and easy way to do it. Personally, this is the technique I would use:

<?php

class MySingleton{
  
  // This will hold the instance of the class
  private static $instance = null;
  
  // Declare this as private to stop anybody being able to use the "new" keyword
  private function __construct()
  {
    // Your usual constructor stuff in here
  }

  // This is where you get your instance
  public static function getInstance()
  {
    if(is_null(self::$instance)){
      self::$instance = new self();
    } 
    return self::$instance;
  }

}

All we’re doing here really, in a set of steps:

  • You need a way to hold an instance of the object which is persistent throughout the execution
    This is what the private static $instance is doing
  • You don’t want anybody to be able to directly use the new keyword, because then you’ve lost control of the instances of the object
  • You need to be able to get an instance of the class, which is what the getInstance method is for
  • In getInstance all we’re doing is instantiating the object if one hasn’t get been stored against the $instance static

So, to fetch your instance is simply:

$singleton = MySingleton::getInstance();

Wherever you run that throughout your code you will receive the exact same instance. Particularly useful in things like Database connections, loggers/debuggers and things like that.

When to use GitHub, when to use BitBucket

This is always a bit of a hot topic, especially amongst teams just getting ready to start properly managing their code through remote repositories.

Disclaimer: I’m only going to talk about GitHub and BitBucket in this article. If your code is your bread and butter, your only offering; you probably should consider hosting your repositories yourself. I’m also sticking with these two as they’re the most widely adopted.

When should I use GitHub?

GitHub can be found at github.com – shameless plug, my user on there is @johnothecoder

Short answer: For anything/everything open source, or where you’d hope for community feedback and maybe even code contributions.

Personally, anything Open Source I think massively benefits from being on GitHub; it’s much more community orientated and you can host as many open/public repositories as you like.

It has some really handy graphs and charts about activity on your repository, and most developers who have anything to do with anything open source will have a GitHub account. On occasion I’ve even been contacted by recruitment agents who have found me through my GitHub, which is kind of cool.

The community on GitHub can be really helpful (though as with all things online there’s always a risk of being flamed) and GitHub, because of its huge market share has ready made integrations, if you’re looking to integrate something into your repository GitHub will almost definitely have it.

When should I use BitBucket?

Short answer: For professional development teams or closed source development

Bitbucket can be found at bitbucket.org

I personally find that, especially for new or small development teams, BitBucket is great. You also get unlimited free private repositories, pricing is instead based on the amount of seats you need (that is, developers on your team who need access to the repository).

So for a professional development team I would always recommend BitBucket, it has all of the features you need – and comes with one very handy thing, which in a professional context gives it, I think, the edge on GitHub: Jira.

Jira is probably, in my experience anyway, the most widely adopted tool for managing development of software. It has a whole host of awesome features, which I’m not going to bang on about as, frankly, they sell it well enough themselves on their website.

However, as most project managers, digital managers, development managers and developers have all used Jira the ready made integration really comes in handy. Those integrations, which will also support you if you make the decision to move into agile, are really handy for growing teams.

Comparison

When it comes to both of these tools (GitHub and BitBucket) they share a lot of handy functionality, which is one of the reasons I’ve never particularly wanted to stray (GitLab can be hosted on your own server and comes with these functionalities too); these features include bug/issue management, wiki, Packagist integration and various other things.

Realistically they’re no better or worse than one another – GitHub comes with integration into Basecamp as standard so that could be handy for digital agencies. Realistically, they will both serve you very well.

Links

GitHub: github.com

BitBucket: bitbucket.com

GitLab: gitlab.com

How Eloquent breaks the Single Responsibility Principle, and why I’m okay with it

Hi everyone

I thought I would discuss a controversial one today, in order to give an articulated response to a common argument about Eloquent (and generally the Active Record pattern)

Firstly, just in case you don’t know, here are some definitions:

Single Responsibility PrincipleThe “S” in the “SOLID” principles. In short, this means one class should have one job. The idea is to keep your code modular and easy to switch out.

SOLID Principles: I’ll do an article on this one day, but it’s a discussion for another time. Like all principles or methodologies they’re like the Pirate’s Code, they’re more like guidelines than hard and fast rules of software design.

Eloquent: Is an ORM (object relational model) which comes as standard with Laravel, and is absolutely fantastic

Active Record: Is a design pattern whereby a record from a database table is returned as an object that can be manipulated and can update the database as part of its role. Usually this means you can do something like

$myRecord = RecordFactoryOrSomething::getTheRecord();
$myRecord->field = 'Updated Value';
$myRecord->save();

This is quite handy for programming as you can store all of the logic to do with saving in the Model.

Laravel: Is a framework for Rapid Application Development, which, like Eloquent, is amazing. It basically gives you all of the tools you need to build bespoke software, but in a way that means you can do it at lightening speed, with crazy accuracy. I can’t sell Laravel well enough, honestly it’s amazing.

So, now that the introductions are out of the way; the Single Responsibility Principle isn’t mandatory

I’d like to make my first point, which quite simply is: The Single Responsibility Principle is a principle. I joked earlier about principles being like the Pirate’s Code, but one does have to be careful when using design patterns and principles, if we’re not careful they become anti-patterns which essentially means their over usage and religious subscription actually causes more problems in the software than it would’ve done had it have been omitted completely.

All patterns should be used in a way which makes sense and makes the code more efficient and maintainable. Ultimately maintainable code which is easy to extend is cheaper for the business whose employing you. Or means your profit margin is higher if you’re running your own business, freelancing or contracting.

Single Responsibility is pretty subjective

This is another slight issue I have with the Single Responsibility Principle. I actually love the principle itself. It makes sense, separate things into logical blocks, and if each class has its own responsibility (and only the one) then it’s quite easy to find how the classes are supposed to work together, perfick.

However, a single responsibility has to be defined. If you defined the single responsibility of a class as “do the business logic” then you could have a God class, which technically has a single responsibility. That would, obviously be a bad usage.

So, let’s look at the other end of the spectrum and go into tiny, tiny detail. Do I need a class for executing SQL queries, and one for generating them? Maybe that means I need a class which prepares INSERT statements, another for UPDATE, and so on and so forth.

The latter approach to single responsibility is most definitely an anti-pattern. That level of abstraction and obscurification will only ever be bad for managing and debugging code.

So then how does the Eloquent Model break it?

The big problem people have with Eloquent is that the Model class fulfils multiple responsibilities. You can’t really say “it is responsible for interacting with a specific table” because it is also representational of a record.

That means it has, at least, two responsibilities: Executing queries against a table, and representing a record. The power of the Eloquent Model is that it actually does more than that, it also defines relationships etc.

So, let’s be honest, it rips the Single Responsibility Principle apart, but I’m totally okay with that.

But, if you love SRP, how can you like the Eloquent Model, you heathen?

The reason I love it, is because what you actually do is group those few responsibilities in an entirely sensical and logical place, you end up with a class which can give you lots of information; all of those responsibilities can be so beautifully wrapped; as so you end up with something like this:

NB: I’ve omitted a lot of code here, just to demonstrate my point I didn’t need it

class User extends Model
{

    // This is a query run against the table
    public static function findUserOnEmail($emailAddress){}

    // This is an action (probably running a query)
    public function changeUserLevel($userLevelId){}

    // This is a relationship defined
    public function friends()
    {
        return $this->hasMany('\ModelNamespace\Friendship');
    }

}

And there you have it, in a few lines of code we have some functionality we need on the table to complete search functionality which has to otherwise be stored somewhere else, that usually doesn’t make sense.

You’ve got an action that can be publicly exposed to other developers to carry out a task without any prior knowledge of the data architecture of your system or how the user levels.

And you’ve got an easy way to get all of the friends for that user.

This is why I love Eloquent. Because it puts aside rules and methodologies for a logical and sensical reason, in order to provide an exceptionally transparent way to manage your data layer.

But wait, there’s more!

All of this is without things like the hookable functions so you can do certain functionality (think expire memcached objects, etc) based on creation, update, or save. There’s a huge amount of functionality built in, and it’s perfect for almost everything.

I’ll be honest, all ORMs fall down with certain complex queries – but it’s not supposed to tackle that problem. It’s the vast majority of monotonous tables and relationships which have to be constantly created to support any kind of enterprise software which becomes so much faster.

Alright, so what’s the alternative?

The alternative to this, realistically, is the Service-Mapper-Entity pattern. In short this means each table has an Entity responsible for representing the data. You then have a Mapper responsible for executing SQL, and then you have a Service which is the interface exposed to the rest of the application. So you tell your service to do something, and it does this using the Mapper, usually returning Entities.

Personally, that feels like too much code to do a simple task. And it is just a personal opinion and there are times that this is very useful, the thing that makes me really sway from that is that when I create 5 tables, with, let’s say 3 bridging tables to support many-to-many relationships; I suddenly can end up with 8 sets of Service, Mappers and Entities. This is 24 classes, which is a lot, compared to 8 classes; which define their relationships and are ready to be used with hydration and all of that stuff.

So, it’s okay to break the Single Responsibility Principle?

Before I ignite an absolute flame war, which this particular topic has the potential to do. In a word, yes. But only if you have a good reason, and you’ve done it to make your code maintainable, readable and easy to manage; without sacrificing security or anything like that.

In this particular instance, I think breaking the principle is fine. It makes sense, and it makes for, even on large scale applications with a large data layer, an easy way of managing this data layer and managing it in a way which is sustainable moving forward.

And how do I keep it clean?

For me personally, follow two major rules.

  1. Static methods do something to the table itself – this could be searching, filtering, retrieving, etc.
  2. Methods on the class, do something to the record – I often like to wrap common functionality in a method, it makes it easily accessible to everyone else

For example; let’s say we activate a user account, there are two ways of approaching this:

// Fetch the record with ID of 17
$record = User::find(17);

// Set the is_user_active field to 1
$record->is_user_active = 1;

// Save this record
$record->save();

There isn’t necessarily anything wrong with this. Until I want to hook into that functionality, or I change something else, let’s say I nullify the activation_key field, for example. Then I would have to go and find everywhere I’ve done this. I don’t like this, it’s a bit awkward.

So I prefer to do something like this

// Fetch the record with ID of 17
$record = User::find(17);

// Activate the record
$record->activate();

// Within your User model class
public function activate()
{
    $this->is_user_active = 1;
    $this->save();
}

Disclaimer: You can do this using the updated method on in Eloquent, so you could hook into this and check to see if the is_user_active field has changed and then hook in that way; word of caution with that though – you can end up with a hell of a lot of if statements and it can get quite messy.

In summary, Eloquent is awesome

  1. It let’s you have an easy to manage data layer for your application
  2. The Model class does break the Single Responsibility Principle, but it can be argued that Model class is responsible for representing and interacting with a single table
  3. You end up with easy to plug into user-land code
  4. You can manage your relationships beautifully

So really, when weighing that up I can’t see any reason not to use it. It’s extendible (I’ve extended the base Eloquent Model multiple times, with a lot of success), you can overwrite functionality where you want to really easy – though you don’t often need to, because the functions you can plug into are so useful.

As always I’d be really interested to hear any thoughts you guys have on this, especially as I know it’s a bit of a controversial one!