A
A
Alexander2019-07-24 12:02:37
PHP
Alexander, 2019-07-24 12:02:37

How to extend an existing model in PHP?

There is a Message class with filled data. title and text.
We need to add the getUrl method, which will be calculated. But not in this class, but in another. Something like MessageExtend which will extend the Message class.
But the question is that I only have Message available. I need to somehow convert it to MessageExtend with the properties of my instance filled in. I have a small blunt here: how is this done in a normal way?
In one place, I implemented it like this: there is a constructor in the MessageExtend class into which the Message is passed, there we loop through the properties of the object and fill it. Elsewhere is the "service" class. Which simply takes an instance of an object and already works with it.
Somehow I missed this moment. I will be glad to help.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
serginhold, 2019-07-24
@neokortex

how to first answer the question "where is it needed and why"
Do not do oop for the sake of oop, just add the getUrl() method to the Message class
Message is some kind of third-party class, and there is no way to change it, so we make a decorator over it.

class MessageDecorator
{
    private $message;

    public function __construct(Message $message)
    {
        $this->message = $message;
    }

    public function getTitle()
    {
        return $this->message->getTitle();
    }
    
    public function getText()
    {
        return $this->message->getText();
    }

    public function getUrl()
    {
        // create url
        return 'url';
    }
}

$message = new MessageDecorator(new Message($title, $text));
$url = $message->getUrl();

Move url generation to a separate service
class UrlService
{
    public function getMessageUrl(Message $message)
    {
        // create url
        return 'url';
    }
}

$message = new Message($title, $text);
$urlService = new UrlService();
$url = $urlService->getMessageUrl($message);

B
bkosun, 2019-07-24
@bkosun

It's called "Inheritance"
https://www.php.net/manual/en/language.oop5.inheri...
https://www.php-fig.org/psr/psr-4/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question