kreghx
3 months ago

Good PHP Design issue

Posted 3 months ago by kreghx

Hello,

I have a question on what to do when you have too many parameters in the construct. How I currently solve it is to create a fluent API with a lot of setters to fill up the data like below :

        $create_payment = new CreatePayment();

        $result = $create_payment->setAmount($amount)
            ->setMethod($method)
            ->setCoupon($coupon)
            ->setGA($ga)
            ->setUser($user)
            ->create();

I am wondering how and if I should refactor this? In one of the Laracast tutorials it said that if you have too many parameters you should create a class for it. Which could end up as this for example:

        $create_payment = new CreatePayment($paymentDataClass);

But then I end up with the same issue that I need to fill up the $paymentDataClass with all the values. I'm just moving the issue of many parameters to another class.

How can I solve this? Or am I doing it right?

For another reference, when I create a ticket for Freshdesk, I've also created a class with many setters to fill up the data to send to Freshdesk.

        $ticket->addEmail($email);
        $ticket->addSubject($subject);
        $ticket->addMessage($message);
        
        
        $ticket->addAttachment($files);

        if (!$ticket->sendTicket()) {
            return ["success" => false, "message" =>  __('messages.ticket_failed')];
        }

Every time I face the issue of too many parameters in construct, I'm moving it to setters right now.

Please sign in or create an account to participate in this conversation.