Smart architecture for controller / views (body / header / footer) in CodeIgniter 3 |
I work with CodeIgniter for two years now. I'm the founder of Friconix and many other websites. All my website are based on CI 3. I love CI 3 because it is simple and fast.
My last website keyller.io (currently under development) has a client-side JS engine and my architecture was no longer well suited. I spend a lot of time on the Internet searching for the best practice for creating modular and well structured controllers/views. This morning, I had (what I believe being) a great idea for building the views in CI3. I just want to share it with you for the following reasons:
I only display one view containing the page. Here is my main view: Code: <?php defined('BASEPATH') OR exit('No direct script access allowed'); ?> You'll easily understand it can be extended with JavaScript or any front-end add-on. Controller Here is my controller source code: Code: $data['header'] = (ENVIRONMENT === 'production') ? $this->load->view('templates/google-analytics', '', TRUE) : '' Look how beautiful and clear is the source code. You no longer have markup opened in one view and closed in another. Each view is now dedicated to one and only one thing. Last, but not least, I love the way views are concatenated : method chaining pattern, so beautiful, I'm so proud . It can potentially even being recursive, you can include views in views in views in views. Question 1: I would like to overload the method $this->load-view to add one parameter (display or not) to replace the following line : Code: .((!$logged) ? $this->load->view('templates/modal-login', '', TRUE) : ''); Code: .$this->load->myView('templates/modal-login', '', TRUE, !$logged); What is the best practice to overload this method ? Note that I never modified the CI core, I will not start today! Question 2: The following code is the same on many pages. I would like to create a function that can be called from any controller. Code: $data['header'] = $this->load->view('templates/javascript', '', TRUE) In your opinion, where should I place this function? Helper?
CodeIgniter 3 has a nice hidden gem that's great for this, see below code.
PHP Code: public function getHeader() What did you Try? What did you Get? What did you Expect?
Joined CodeIgniter Community 2009. ( Skype: insitfx )
(01-05-2020, 09:18 AM)InsiteFX Wrote: CodeIgniter 3 has a nice hidden gem that's great for this, see below code. Interesting, it's still not clear for me where the function should be placed.
I would create a MY_Controller and extend all of your controllers from the MY_Contoller.
You could then put all of your methods into it. Or if you like create a view_helper and place all your view methods in it. What did you Try? What did you Get? What did you Expect?
Joined CodeIgniter Community 2009. ( Skype: insitfx )
|
Welcome Guest, Not a member yet? Register Sign In |