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

Ligonsker's avatar

Repeating code specific to the controller

Hi,

I've asked a similar question long time ago, so from the answers there didn't seem to be a conclusive answer.

I have repeating code that is specific to a controller. For example, constructing a string from input and validating it, or a repeating query that isn't used directly by a route.

What I do right now is I simply create functions inside the controller, sometimes without passing the $request to them, and sometimes passing it for the data. I then call these functions from inside the controller:

$result = $this->some_function();

It's working, but would you do something else? I feel like I should not put them in another folder like app/Support or similar folder because these functions are controller-specific

But I also feel like it's "polluting" the code

Should I do something else or just leave it like that?.

Thanks

0 likes
4 replies
Pixolantis's avatar

As I don't know exactly what you do in your function, it is difficult to give specific recommendations. If it is only for the controller and it concerns the data of a model, the consideration would be to work with accessors/mutators If it is only for the controller and it concerns the data of a model, it might be an idea to work with accessors/mutators

Another option would be to create a custom helper

1 like
jeffallen's avatar

You can make a custom helper class and put it in there.

1 like
CrypticCoder's avatar

create helper inside app/helpers.php

function  some_function(){
$data = 'blah blah";
return $data ;
}
//than in controller or wherever you want to call this function 
1 like
Snapey's avatar

Do it as you are doing. If the code only relates to the one controller, keep it in the controller.

If the code is to manipulate the request data I would also consider putting it in a form request class.

1 like

Please or to participate in this conversation.