Home > Back-end >  New class without passing constructor variables
New class without passing constructor variables

Time:11-13

Probably a stupid question but what is the best way to do this?

So, I am using the two parameters in Emailservices' construct which are the entity manager and email factory.

The problem is that I want to call a function of this class from another, without adding these two parameters. It's needless to add these two in this case.

When i do $emailService = new EmailService(); i get the error too few arguments to function but if i pass the class EmailService $emailService as a parameter into SendPaymentEmail then it works - can you explain me why and what's the best approach here?

class EmailService
{
    private EntityManagerInterface $entityManager;
    private EmailFactory $emailFactory;

    public function __construct(EntityManagerInterface $em, EmailFactory $emailFactory)
    {
        $this->entityManager = $em;
        $this->emailFactory = $emailFactory;
    }

public function sendPaymentEmail(User $user)
{
    $emailService = new EmailService();
    $sender = $this->container->get('twig')->getGlobals()['email_no_reply'];

    return $emailService->sendPaymentEmail($sender, $user, 'customer_home');
}

Error: Too few arguments to function App\Service\EmailService::__construct(), 0 passed in /var/www/html2/app/src/Service/PaymentService.php on line 36 and exactly 2 expected

CodePudding user response:

You should use in Symfony dependency injection and autowiring, read more in official documentation (remember to choose symfony version you’re using): https://symfony.com/doc/current/service_container/autowiring.html

CodePudding user response:

i cant understand your question is a little unclear but if you want to call a method of some class (without make an instance) from another class or function etc, you must to make the method static for example:

public static function sendPaymentEmail(User $user){...};

the call it like:

EmailService::sendPaymentEmail($user);
  • Related