I have two subclasses and I want to call a method in one subclass from another. Is the only solution to start chaining my classes in order of dependence? Sorry for the noob PHP question. Basically it's a common scenario to have multiple "base" classes such as an email class in which other subclasses will need access to. So do you just starting chaining them?
// BaseClass.php
require_once("./services/checkout.php");
require_once("./services/email.php");
class Base {
// ...
}
// checkout.php
class checkout extends Base {
public function onCheckout() {
// Call send email
$this->sendEmail($email); // <- How to do this?
}
}
// email.php
class email extends Base {
public function sendEmail($email) {
// Send email
}
}
CodePudding user response:
I think it's common to have BaseAction
or BaseController
but not something as generic as BaseClass
. It feels more intuitive to have something like:
class Checkout
{
public function onCheckout(Mailer $mailer)
{
$mailer->sendEmail($email);
}
}
class Mailer
{
public function sendEmail($email)
{
// Send email
}
}
This is still very rough. You most likely want an interface, injected into checkout
constructor, perhaps automagically with some dependency injection library that implements autowiring:
interface MessengerInterface
{
public function send(string $text): bool
}
class Checkout
{
private $messenger;
public function __construct(
MessengerInterface $messenger
) {
$this->messenger = $messenger;
}
public function onCheckout()
{
$this->messenger->send('Your order blah blah');
}
}
class Mailer implements MessengerInterface
{
public function send(string $body): bool
{
// Send email
}
}
CodePudding user response:
Please read Traits in Php. It seem that would be the right thing for your goal:
PHP-Traits (W3Schools - easier to understand)
I would suggest to reconsider your inheritance, whether it makes sense that E-Mail class and Checkout-Class inherit from the same base class. They should do total different and independent things by their own. If you want to send an e-mail from the checkout-class then try to implement an e-mail class and inject an instance of it to the checkout object.