Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Traits as helpers

Tags:

php

traits

Are there any contradictions to use traits to inject helper methods like this?

   class Foo
   {

       use Helper\Array;

       function isFooValid(array $foo)
       {
            return $this->arrayContainsOnly('BarClass', $foo);
       }

   }
like image 760
Mateusz Charytoniuk Avatar asked Jul 11 '12 05:07

Mateusz Charytoniuk


2 Answers

That's the idea with traits.

However you should still keep an eye out for coupled code. If Helper\Array is a completely different namespace from what Foo is in you might want to re-think this particular approach.

like image 150
Tobias Sjösten Avatar answered Sep 22 '22 13:09

Tobias Sjösten


Traits have been added to PHP for a very simple reason: PHP does not support multiple inheritance. Simply put, a class cannot extends more than on class at a time. This becomes laborious when you need functionality declared in two different classes that are used by other classes as well, and the result is that you would have to repeat code in order to get the job done without tangling yourself up in a mist of cobwebs.

Enter traits. These allow us to declare a type of class that contains methods that can be reused. Better still, their methods can be directly injected into any class you use, and you can use multiple traits in the same class. Let's look at a simple Hello World example.

<?php

trait SayHello
{
    private function hello()
    {
        return "Hello ";
    }

    private function world()
    {
        return "World";
    }
}

trait Talk
{
    private function speak()
    {
        echo $this->hello() . $this->world();
    }
}

class HelloWorld
{
    use SayHello;
    use Talk;

    public function __construct()
    {
        $this->speak();
    }
}

$message = new HelloWorld(); // returns "Hello World";
like image 26
PankajR Avatar answered Sep 18 '22 13:09

PankajR