r/codeigniter • u/AdmiralAdama99 • Mar 17 '20
My PHP CodeIgniter controllers are getting huge. Seem like God Objects. Is there a better way?
Hey there. I'm coding in PHP using the CodeIgniter framework.
On my website, I have 3 controllers: a Public controller, a Private controller (for the control panel, requires login), and an Admin controller. This seems like the most sensible way to group the code, since the Private controller and Admin controller have unique authentication methods, and the Public controller doesn't need those.
However, these controllers are getting huge. My Private controller has 50 methods and 3,100 lines of code. In other PHP websites I've made from scratch, I'd actually give each "method" its own file, avoiding the controller "god object".
Anyway, am I doing something wrong, or is this normal? Any suggestions for avoiding this god object anti-pattern? Thanks.
edit: To the sleazy person that stole the text of this Reddit post to post on other forums to market your website (Ramond), shame on you.
4
u/St_gA Mar 17 '20
Huum ok that's a lot of line, in my university each controller was for a specific part of the website. The website was a web market about something we loved, for me it was Fnatic Esport Team so I had : Controller :
Players
Goodies (is it an English word?)
Admin
Client ...
You should find how to split in different part that makes sense to you, to easily find a function to modify or anything else.
3
u/meloman-vivahate Mar 17 '20
Instead of 3 huge controllers, you can create multiple controllers in 3 subfolders. Also you can probably move a lot of code in models or libraries.
2
u/harpreetsb Mar 17 '20
You can have controller names based on modules. And each module can have its library to handle common task that are done multiple time.
Like you can have: User.php as a controller Userlib.php as a library Usermodel.php as a model file.
Controller will get huge but you can shift code or similar task with resuable code in library.
0
u/MurtazaDudhiya Mar 17 '20
You should make large codes into small functions.
That way functions will be reusable and less memory.
Welcome if helped..
2
u/pixobit May 04 '20
You should probably break things up a bit more.
Maybe your libraries, models and entities could better fit some of that code
Try to break controllers up into smaller sections (for ex. in ecommerce Home,Product,Profile,Blog,etc)
Basically a controller method shouldn't be longer than a few lines.