G
G
gerassim2015-11-17 13:20:01
PHP
gerassim, 2015-11-17 13:20:01

How to change type of method parameter in php on override?

Let's say we have two interfaces

interface Message {
    function send();
    function setSender(Sender $sender);
}

interface Sender {
    function send(Message $message);
}

And specific implementations
class EmailMessage implements Message {
    private $sender;

    public function setSender(Sender $sender) {
        $this->sender = $sender;
    }
    function send() {
        $this->sender->send($this);
    }
}

class SmtpEmailMessageSender implements Sender{
    private $server;
    private $login;
    private $password;

    public function __construct($server, $login, $password) {
        $this->server = $server;
        $this->login = $login;
        $this->password = $password;
    }

    function send(Message $message) {
         ..... код отправки.....
    }
}

How to make SmtpEmailSender only accept EmailMessage to send, and not any Message?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alex Safonov, 2015-11-17
@gerassim

class SmtpEmailMessageSender implements Sender
{
  private $server;
  private $login;
  private $password;

  public function __construct($server, $login, $password)
  {
    $this->server   = $server;
    $this->login    = $login;
    $this->password = $password;
  }

  function send(Message $message)
  {
    if( !($message instanceof EmailMessage) ){throw new InvalidArgumentException("Instance of 'EmailMessage' expected. Got '".get_class($message)."'");}
    //...
  }
}

This is the only solution that exists for your case.
Another thing is that you have some implicit restriction. That *suddenly* the interface is universal, but in this case not completely. Let's take as input not everyone who implements our interface, but only one class.
It is not right.
Make a different interface and let your EmailMessage implement it. Because the Interface Separation Principle is a pretty reasonable approach to writing code. And in particular, there can be no universal beautiful abstraction, which you illustrated. (many client-specific interfaces are better than one general-purpose interface)
Rename your interfaces to match the PSR .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question