artisanRunner liked a comment+100 XP
4mos ago
The 'feature filters' described here are an implementation of the Interface Segregation Principle, or to put it simply, keeping interfaces focused on one specific task:
interface HasAuthor()
{
public string $author { get; set; }
}
interface HasContent()
{
public string $content { get; set; }
}
interface CanBeLiked()
{
public function like(): void;
public function isLiked(): bool;
}
class Post implements HasAuthor, HasContent, CanBeLiked
{
public string $author = '...';
public string $content = '...';
public function like(): void { ... }
public function isLiked(): bool { ... }
}
This principle is more achievable in PHP now that we have Intersection Types. For example:
class Thread
{
/** @var HasAuthor&HasContent&CanBeLiked[] */
private array $replies = [];
public function __construct(private HasAuthor&HasContent $subject)
{
}
public function display()
{
echo $this->subject->content . '<br>';
echo 'Author: ' . $this->subject->author . '<br><br>';
foreach ($this->replies as $reply) {
echo $reply->content . '<br>';
echo 'Author: ' . $reply->author . '<br><br>';
if ($reply->isLiked()) {
echo '(Someone has liked this reply!)<br><br>';
}
}
}
}
The Thread class doesn't know anything about a Post class; it just knows that its $subject property must implement both HasAuthor and HasContent interfaces and that $replies must be an array of elements implementing (via static analysis), HasAuthor, HasContent, and CanBeLiked. These could be instances of Post, Comment, Letter, Car, Dog... anything really. Thread doesn't care.
It's easy to go overboard with this approach, creating dozens of tiny interfaces with massive intersectional types. As with much in coding, try to strike a balance between readability and loose coupling!
artisanRunner liked a comment+100 XP
4mos ago
artisanRunner liked a comment+100 XP
4mos ago
artisanRunner liked a comment+100 XP
4mos ago
@Kobzon Thank you!
artisanRunner liked a comment+100 XP
4mos ago
Best php course I've ever seen. Thanks @jeffreyway !
artisanRunner liked a comment+100 XP
4mos ago
artisanRunner wrote a comment+100 XP
4mos ago
@JeffreyWay you're the best mentor! Thanks a lot for this course!
artisanRunner liked a comment+100 XP
4mos ago
@junaidqadir There's an old saying in chinese. "He who by reviewing the old can gain knowledge of the new and is fit to be a teacher. "

artisanRunner liked a comment+100 XP
4mos ago
artisanRunner wrote a reply+100 XP
4mos ago
artisanRunner liked a comment+100 XP
4mos ago