PHP - Traits as helpers

拈花ヽ惹草 提交于 2019-12-04 23:59:07

问题


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);
       }

   }

回答1:


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.




回答2:


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";



回答3:


In my opinion and talking about cohesion within an application, distributing responsibilties is a good thing but scattering responsibilties is really something else that have nothing to do with design by contract. This is my concern with traits as helpers. I've been thinking a lot about traits place in an architecture and I really think traits should be taken for what they are : shared implementation meaning shared encapsulation. So they should not replace interfaces but stay behind them. I take "interface" in the architectural and language-agnostic sense not idiosyncratic sense given the fact that PHP-specific interfaces are just an abstraction tool whereas traits are nothing but an implementation tool. Interfaces come before implementations.Rely on abstract/interfaces and not on concrete/details. So it's important to keep in mind that traits don't structure application architectures no more they initiate class contracts but stand behind them and at the service of them.



来源:https://stackoverflow.com/questions/11426301/php-traits-as-helpers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!