Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

kreghx's avatar

Good PHP Design issue

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.

0 likes
2 replies
martinbean's avatar
Level 80

@kreghx Theres no hard and fast rule when it comes to structuring, organising, and writing code. If there were, machines would already be doing it ;)

In the case of lots of parameters in a class constructor, its an indication (and only an indication) that the class may be doing too much. Youll just need to look classes on a case by case basis when you find it requires lots of parameters to see if the class accurate models an entity in your application, or whether there may be smaller, more appropriate objects that could be extracted. Without concrete examples, thats hard to advise on.

In the example you did provide (the create payment class) it looks similar the subscription builder class in Laravel Cashier. I dont know your application, but I imagine a coupon is optional for creating a payment? If this is the case, then it doesnt need to be a parameter in your classs constructor.

Your class constructors should require the least number of parameters possible to instantiate a valid instance of that object. Any additional attributes can be supplied using other class methods (i.e. withCoupon($coupon)).

kreghx's avatar

Thanks I will keep it all in mind

Please or to participate in this conversation.