Traits to keep classes clean

suggest change

Over time, our classes may implement more and more interfaces. When these interfaces have many methods, the total number of methods in our class will become very large.

For example, let’s suppose that we have two interfaces and a class implementing them:

interface Printable {
    public function print();   
    //other interface methods...
}

interface Cacheable {
    //interface methods
}

class Article implements Cachable, Printable {  
    //here we must implement all the interface methods
    public function print(){ {
        /* code to print the article */ 
    }
}

Instead of implementing all the interface methods inside the Article class, we could use separate Traits to implement these interfaces, keeping the class smaller and separating the code of the interface implementation from the class.

From example, to implement the Printable interface we could create this trait:

trait PrintableArticle {
    //implements here the interface methods
    public function print() {
        /* code to print the article */ 
    }
}

and make the class use the trait:

class Article implements Cachable, Printable {
    use PrintableArticle;
    use CacheableArticle; 
}

The primary benefits would be that our interface-implementation methods will be separated from the rest of the class, and stored in a trait who has the sole responsibility to implement the interface for that particular type of object.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Traits:
* Traits
* Traits to keep classes clean

Table Of Contents
2 Arrays
4 Types
10 Cookies
14 JSON
15 SOAP
17 cURL
19 XML
21 Traits
35 UTF-8
36 URLs
38 PHPDoc
41 Loops
44 Closur
72 YAML
77 Cache
78 Streams
81 PDO
82 SQLite3
83 Sockets
87 MongoDB
93 IMAP
94 Redis
95 Imagick
102 APCu
108 PSR