Traits in PHP

If you worked with abstract objects before, you are aware of the single inheritance limitation, traits fix this in a very elegant way to allow us to write re-usable code.

Creating traits

Traits are created using the trait keyword:


trait MyTrait {

    function my_function()
    {
       echo 'My first trait';
    }

}

Using traits

To add a trait to a class, use the use keyword within the class:


class MyClass {

    use MyTrait;

}

That’s it! now you have all the trait’s methods available, to use multiple traits you can declare them on the same line separating them with a comma:


class MyClass {
    use MyTrait, MySecondTrait;

}

Note: traits can’t be instantiated.

PSR-4 and Laravel

If you didn’t already know, psr-* is a php standard for auto-loading classes, it stands for PHP Specification Request, psr-4 is the latest version.

PSR-4 offers great flexibility, you can define namespaces with any location, for example we might use Acme namespace that looks for classes in a folder called app/BusinessLogic/ and later on, if you want to change the location you just change the location where you declare the namspace(composer.json) without touching any of you files.

PSR-4 namespace(s) can be defined within composer.json in autoload section:


"autoload": {
		"classmap": [
			"app/database/migrations",
			"app/database/seeds"
		],

        "psr-4": {
            "Acme\\": "app/BusinessLogic/",

        }
},

Note: “\\” is required at the end.

Let’s say we have class A inside BusinessLogic/, we will define Acme namespace and access the class like this:


new Acme\A();

PHP get last month in March bug

This post is not laravel related, but is a big bug in PHP regarding how it handles months, especially February.

If you need  the last month, today(March 29), with one of the following ways



 date('Y-m-d', strtotime('-1 Month'));

 date('Y-m-d', mktime(0,0,0,date("m")-1,date("d"),date("Y")) );

 $date = new DateTime();
 $date->modify("-1 Month");
 $date->format("Y-m-d");


They all return “2013-03-01”, which can screw up your applications big time.

The solution is:


 date('Y-m-d', strtotime('first day of last month'));

Which returns “2013-02-01”;