Codeigniter 3: how can I avoid repeating this chunk of code in my controllers?Applying MVC to a validation...

What do the Banks children have against barley water?

LWC and complex parameters

If a centaur druid Wild Shapes into a Giant Elk, do their Charge features stack?

Is Social Media Science Fiction?

Typesetting a double Over Dot on top of a symbol

How to make payment on the internet without leaving a money trail?

Can I find out the caloric content of bread by dehydrating it?

Why is my log file so massive? 22gb. I am running log backups

Is domain driven design an anti-SQL pattern?

Calculate Levenshtein distance between two strings in Python

Are objects structures and/or vice versa?

Denied boarding due to overcrowding, Sparpreis ticket. What are my rights?

Are cabin dividers used to "hide" the flex of the airplane?

COUNT(*) or MAX(id) - which is faster?

Could a US political party gain complete control over the government by removing checks & balances?

How to manage monthly salary

Is it wise to focus on putting odd beats on left when playing double bass drums?

Symmetry in quantum mechanics

extract characters between two commas?

What does 'script /dev/null' do?

Is a vector space a subspace?

How to deal with fear of taking dependencies

Unbreakable Formation vs. Cry of the Carnarium

Can I legally use front facing blue light in the UK?



Codeigniter 3: how can I avoid repeating this chunk of code in my controllers?


Applying MVC to a validation applicationBest practice for generating jQuery dynamical contentCodeIgniter maintain data through ControllersFor a login portal, what security measures are needed to prevent unauthorized access?Handle data insertion after validationVery basic PHP session handlingVolunteer Signup PageReduce repetition when sharing data across an applicationPHP code to show a PHP pageRudimentary registration and login system






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ margin-bottom:0;
}







0












$begingroup$


I am working on a basic blog application in Codeigniter 3.1.8 and Bootstrap 4.



Several entities are present in all controllers (except Login.php and Register.php): static data, categories and pages.



$data = $this->Static_model->get_static_data();
$data['pages'] = $this->Pages_model->get_pages();
$data['categories'] = $this->Categories_model->get_categories();


Further more, in most controller, the code above appears more then one time.



I am afraid this is mot the only case of repetitive code in the application. (See the entire application, at its current state, on my Github account).



I am looking for specific and/or general advice from experienced PHP developers that would help me reduce code redundancy and make it more efficient.



What is the best way to avoid the repeating of the code above in my controllers?










share|improve this question









$endgroup$












  • $begingroup$
    Instead of this $this->Static_model why not make a new config for this data, it seems like a better way. Because you can then create a development copy etc. codeigniter.com/user_guide/general/…
    $endgroup$
    – ArtisticPhoenix
    10 hours ago


















0












$begingroup$


I am working on a basic blog application in Codeigniter 3.1.8 and Bootstrap 4.



Several entities are present in all controllers (except Login.php and Register.php): static data, categories and pages.



$data = $this->Static_model->get_static_data();
$data['pages'] = $this->Pages_model->get_pages();
$data['categories'] = $this->Categories_model->get_categories();


Further more, in most controller, the code above appears more then one time.



I am afraid this is mot the only case of repetitive code in the application. (See the entire application, at its current state, on my Github account).



I am looking for specific and/or general advice from experienced PHP developers that would help me reduce code redundancy and make it more efficient.



What is the best way to avoid the repeating of the code above in my controllers?










share|improve this question









$endgroup$












  • $begingroup$
    Instead of this $this->Static_model why not make a new config for this data, it seems like a better way. Because you can then create a development copy etc. codeigniter.com/user_guide/general/…
    $endgroup$
    – ArtisticPhoenix
    10 hours ago














0












0








0





$begingroup$


I am working on a basic blog application in Codeigniter 3.1.8 and Bootstrap 4.



Several entities are present in all controllers (except Login.php and Register.php): static data, categories and pages.



$data = $this->Static_model->get_static_data();
$data['pages'] = $this->Pages_model->get_pages();
$data['categories'] = $this->Categories_model->get_categories();


Further more, in most controller, the code above appears more then one time.



I am afraid this is mot the only case of repetitive code in the application. (See the entire application, at its current state, on my Github account).



I am looking for specific and/or general advice from experienced PHP developers that would help me reduce code redundancy and make it more efficient.



What is the best way to avoid the repeating of the code above in my controllers?










share|improve this question









$endgroup$




I am working on a basic blog application in Codeigniter 3.1.8 and Bootstrap 4.



Several entities are present in all controllers (except Login.php and Register.php): static data, categories and pages.



$data = $this->Static_model->get_static_data();
$data['pages'] = $this->Pages_model->get_pages();
$data['categories'] = $this->Categories_model->get_categories();


Further more, in most controller, the code above appears more then one time.



I am afraid this is mot the only case of repetitive code in the application. (See the entire application, at its current state, on my Github account).



I am looking for specific and/or general advice from experienced PHP developers that would help me reduce code redundancy and make it more efficient.



What is the best way to avoid the repeating of the code above in my controllers?







php codeigniter






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked yesterday









Razvan ZamfirRazvan Zamfir

12212




12212












  • $begingroup$
    Instead of this $this->Static_model why not make a new config for this data, it seems like a better way. Because you can then create a development copy etc. codeigniter.com/user_guide/general/…
    $endgroup$
    – ArtisticPhoenix
    10 hours ago


















  • $begingroup$
    Instead of this $this->Static_model why not make a new config for this data, it seems like a better way. Because you can then create a development copy etc. codeigniter.com/user_guide/general/…
    $endgroup$
    – ArtisticPhoenix
    10 hours ago
















$begingroup$
Instead of this $this->Static_model why not make a new config for this data, it seems like a better way. Because you can then create a development copy etc. codeigniter.com/user_guide/general/…
$endgroup$
– ArtisticPhoenix
10 hours ago




$begingroup$
Instead of this $this->Static_model why not make a new config for this data, it seems like a better way. Because you can then create a development copy etc. codeigniter.com/user_guide/general/…
$endgroup$
– ArtisticPhoenix
10 hours ago










2 Answers
2






active

oldest

votes


















2












$begingroup$

I had a very short look at lightblog/application/controllers/Pages.php and I noticed that these two values were not used in the page() method:



$data['pages']
$data['posts']


Then I realized that you hand over data to other objects and they might be using these two values. Who knows? This makes your code very hard to understand and to debug.



Basically you're treating the $data array as a sort of object you hand over to other classes.



But wait, did I say 'object'? But what if it was? Clearly you have a need to keep data accessible, but why use an array that you need to recreate every time? Why not use a class?



Now I don't have any idea how your code is structure, and which class would be the best to use for this. But it would make sense to extend the basic CodeIgniter controller class to hold this data, like so:



class Data_Controller extends CI_Controller 
{
private $data;

public function __construct()
{
parent::__construct();
$this->data = $this->Static_model->get_static_data();
$this->data['pages'] = $this->Pages_model->get_pages();
$this->data['categories'] = $this->Categories_model->get_categories();
$this->data['posts'] = $this->Posts_model->sidebar_posts($limit=5, $offset=0);
$this->data['page'] = $this->Pages_model->get_page($page_id);
}


public function getData()
{
return $this->data;
}

}


or something to the same effect and then extend this for your pages class:



class Pages extends Data_Controller {

public function __construct()
{
// currently this whole method doesn't do anything, it can be removed
parent::__construct();
}

public function page($page_id) {
$data = $this->getData();
..........................

}

}


And, of course, those controller classes that don't need all that data can just extend CI_Controller.



I'm sure there are other ways of doing this. I don't like the fact that now you still collect all that information without actually knowning if it is needed. I would make the retrieval of the data dependent on the fact that it is actually used. In other words use getter methods, not a data array. I'll give an example for 'pages' and 'posts', but you have to create the other ones yourself:



class Data_Controller extends CI_Controller 
{

public function getPages()
{
return $this->Pages_model->get_pages();
}

public function getCatagories()
{
return $this->Categories_model->get_categories();

}

}


If you need to buffer the data you can do:



class Data_Controller extends CI_Controller 
{

public function getCatagories()
{
static $buffer = NULL;
if (is_null($buffer)) $buffer = $this->Categories_model->get_categories();
return $buffer;
}

}


Keep in mind that this buffer will work for all instances of Data_Controller. That can be an advantage, or a disadvantage.



OK, that was a bit long. I hope you got some new ideas from my ramblings.






share|improve this answer











$endgroup$





















    0












    $begingroup$

    In this case I would probably convert this $this->Static_model into a Config file that I can use through CI (that is what they are there for). You can even make CI load this file automatically, with hook. And you can even load different version based on your ENVIORMENT setting (for testing and what not).



    For the dynamic data, now depending how dynamic this is:



     $data['pages'] = $this->Pages_model->get_pages();


    I would probably use the Caching Driver. Chances are this doesn't update that much, and even when it does you can reset the cache. For example how often will you really add a new category. Certainly not every couple minutes, or even hours.



    One other thing not mentioned



    Avoid changing data types when returning from a method. You may not even realize you are doing it. In some cases its perfectly fine to return mixed data types, but as a general rule you should avoid it as it complicates your downstream code by having to check the return data all the time for it's type.



    I found this quick example (in your code):



    class Categories_model extends CI_Model {

    public function get_category($category_id){
    $query = $this->db->get_where('categories', array('id' => $category_id));
    if ($query->num_rows() > 0) {
    return $query->row();
    }

    } //<-- returns null || array

    }

    class Pages extends CI_Controller {
    public function page($page_id) {

    //...
    $data['categories'] = $this->Categories_model->get_categories(); //returns an array || null
    //...
    //requires a check (null is false, so is [])
    if ($data['categories']) {
    foreach ($data['categories'] as &$category) {
    $category->posts_count = $this->Posts_model->count_posts_in_category($category->id);
    }
    }
    //...
    }
    }


    Instead consider this:



    class Categories_model extends CI_Model {

    public function get_category($category_id){
    $query = $this->db->get_where('categories', array('id' => $category_id));
    if ($query->num_rows() > 0) {
    return $query->row();
    }
    return [];
    }

    }

    class Pages extends CI_Controller {
    public function page($page_id) {
    //...
    $data['categories'] = $this->Categories_model->get_categories(); //always returns an array
    //...
    //requires no type check, as an empty array simply skips the loop
    foreach ($data['categories'] as &$category) {
    $category->posts_count = $this->Posts_model->count_posts_in_category($category->id);
    }
    //...
    }
    }


    This may seem trivial, but it can add up to a lot of code. In PHP7 you can even set return type hints eg. public function get_category($category_id) : array. To insure the return type is consistent etc.



    Really when it comes to programing one of the most important things is consistency.



    Hope it helps!






    share|improve this answer











    $endgroup$














      Your Answer





      StackExchange.ifUsing("editor", function () {
      return StackExchange.using("mathjaxEditing", function () {
      StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
      StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
      });
      });
      }, "mathjax-editing");

      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "196"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: false,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: null,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f217002%2fcodeigniter-3-how-can-i-avoid-repeating-this-chunk-of-code-in-my-controllers%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      2












      $begingroup$

      I had a very short look at lightblog/application/controllers/Pages.php and I noticed that these two values were not used in the page() method:



      $data['pages']
      $data['posts']


      Then I realized that you hand over data to other objects and they might be using these two values. Who knows? This makes your code very hard to understand and to debug.



      Basically you're treating the $data array as a sort of object you hand over to other classes.



      But wait, did I say 'object'? But what if it was? Clearly you have a need to keep data accessible, but why use an array that you need to recreate every time? Why not use a class?



      Now I don't have any idea how your code is structure, and which class would be the best to use for this. But it would make sense to extend the basic CodeIgniter controller class to hold this data, like so:



      class Data_Controller extends CI_Controller 
      {
      private $data;

      public function __construct()
      {
      parent::__construct();
      $this->data = $this->Static_model->get_static_data();
      $this->data['pages'] = $this->Pages_model->get_pages();
      $this->data['categories'] = $this->Categories_model->get_categories();
      $this->data['posts'] = $this->Posts_model->sidebar_posts($limit=5, $offset=0);
      $this->data['page'] = $this->Pages_model->get_page($page_id);
      }


      public function getData()
      {
      return $this->data;
      }

      }


      or something to the same effect and then extend this for your pages class:



      class Pages extends Data_Controller {

      public function __construct()
      {
      // currently this whole method doesn't do anything, it can be removed
      parent::__construct();
      }

      public function page($page_id) {
      $data = $this->getData();
      ..........................

      }

      }


      And, of course, those controller classes that don't need all that data can just extend CI_Controller.



      I'm sure there are other ways of doing this. I don't like the fact that now you still collect all that information without actually knowning if it is needed. I would make the retrieval of the data dependent on the fact that it is actually used. In other words use getter methods, not a data array. I'll give an example for 'pages' and 'posts', but you have to create the other ones yourself:



      class Data_Controller extends CI_Controller 
      {

      public function getPages()
      {
      return $this->Pages_model->get_pages();
      }

      public function getCatagories()
      {
      return $this->Categories_model->get_categories();

      }

      }


      If you need to buffer the data you can do:



      class Data_Controller extends CI_Controller 
      {

      public function getCatagories()
      {
      static $buffer = NULL;
      if (is_null($buffer)) $buffer = $this->Categories_model->get_categories();
      return $buffer;
      }

      }


      Keep in mind that this buffer will work for all instances of Data_Controller. That can be an advantage, or a disadvantage.



      OK, that was a bit long. I hope you got some new ideas from my ramblings.






      share|improve this answer











      $endgroup$


















        2












        $begingroup$

        I had a very short look at lightblog/application/controllers/Pages.php and I noticed that these two values were not used in the page() method:



        $data['pages']
        $data['posts']


        Then I realized that you hand over data to other objects and they might be using these two values. Who knows? This makes your code very hard to understand and to debug.



        Basically you're treating the $data array as a sort of object you hand over to other classes.



        But wait, did I say 'object'? But what if it was? Clearly you have a need to keep data accessible, but why use an array that you need to recreate every time? Why not use a class?



        Now I don't have any idea how your code is structure, and which class would be the best to use for this. But it would make sense to extend the basic CodeIgniter controller class to hold this data, like so:



        class Data_Controller extends CI_Controller 
        {
        private $data;

        public function __construct()
        {
        parent::__construct();
        $this->data = $this->Static_model->get_static_data();
        $this->data['pages'] = $this->Pages_model->get_pages();
        $this->data['categories'] = $this->Categories_model->get_categories();
        $this->data['posts'] = $this->Posts_model->sidebar_posts($limit=5, $offset=0);
        $this->data['page'] = $this->Pages_model->get_page($page_id);
        }


        public function getData()
        {
        return $this->data;
        }

        }


        or something to the same effect and then extend this for your pages class:



        class Pages extends Data_Controller {

        public function __construct()
        {
        // currently this whole method doesn't do anything, it can be removed
        parent::__construct();
        }

        public function page($page_id) {
        $data = $this->getData();
        ..........................

        }

        }


        And, of course, those controller classes that don't need all that data can just extend CI_Controller.



        I'm sure there are other ways of doing this. I don't like the fact that now you still collect all that information without actually knowning if it is needed. I would make the retrieval of the data dependent on the fact that it is actually used. In other words use getter methods, not a data array. I'll give an example for 'pages' and 'posts', but you have to create the other ones yourself:



        class Data_Controller extends CI_Controller 
        {

        public function getPages()
        {
        return $this->Pages_model->get_pages();
        }

        public function getCatagories()
        {
        return $this->Categories_model->get_categories();

        }

        }


        If you need to buffer the data you can do:



        class Data_Controller extends CI_Controller 
        {

        public function getCatagories()
        {
        static $buffer = NULL;
        if (is_null($buffer)) $buffer = $this->Categories_model->get_categories();
        return $buffer;
        }

        }


        Keep in mind that this buffer will work for all instances of Data_Controller. That can be an advantage, or a disadvantage.



        OK, that was a bit long. I hope you got some new ideas from my ramblings.






        share|improve this answer











        $endgroup$
















          2












          2








          2





          $begingroup$

          I had a very short look at lightblog/application/controllers/Pages.php and I noticed that these two values were not used in the page() method:



          $data['pages']
          $data['posts']


          Then I realized that you hand over data to other objects and they might be using these two values. Who knows? This makes your code very hard to understand and to debug.



          Basically you're treating the $data array as a sort of object you hand over to other classes.



          But wait, did I say 'object'? But what if it was? Clearly you have a need to keep data accessible, but why use an array that you need to recreate every time? Why not use a class?



          Now I don't have any idea how your code is structure, and which class would be the best to use for this. But it would make sense to extend the basic CodeIgniter controller class to hold this data, like so:



          class Data_Controller extends CI_Controller 
          {
          private $data;

          public function __construct()
          {
          parent::__construct();
          $this->data = $this->Static_model->get_static_data();
          $this->data['pages'] = $this->Pages_model->get_pages();
          $this->data['categories'] = $this->Categories_model->get_categories();
          $this->data['posts'] = $this->Posts_model->sidebar_posts($limit=5, $offset=0);
          $this->data['page'] = $this->Pages_model->get_page($page_id);
          }


          public function getData()
          {
          return $this->data;
          }

          }


          or something to the same effect and then extend this for your pages class:



          class Pages extends Data_Controller {

          public function __construct()
          {
          // currently this whole method doesn't do anything, it can be removed
          parent::__construct();
          }

          public function page($page_id) {
          $data = $this->getData();
          ..........................

          }

          }


          And, of course, those controller classes that don't need all that data can just extend CI_Controller.



          I'm sure there are other ways of doing this. I don't like the fact that now you still collect all that information without actually knowning if it is needed. I would make the retrieval of the data dependent on the fact that it is actually used. In other words use getter methods, not a data array. I'll give an example for 'pages' and 'posts', but you have to create the other ones yourself:



          class Data_Controller extends CI_Controller 
          {

          public function getPages()
          {
          return $this->Pages_model->get_pages();
          }

          public function getCatagories()
          {
          return $this->Categories_model->get_categories();

          }

          }


          If you need to buffer the data you can do:



          class Data_Controller extends CI_Controller 
          {

          public function getCatagories()
          {
          static $buffer = NULL;
          if (is_null($buffer)) $buffer = $this->Categories_model->get_categories();
          return $buffer;
          }

          }


          Keep in mind that this buffer will work for all instances of Data_Controller. That can be an advantage, or a disadvantage.



          OK, that was a bit long. I hope you got some new ideas from my ramblings.






          share|improve this answer











          $endgroup$



          I had a very short look at lightblog/application/controllers/Pages.php and I noticed that these two values were not used in the page() method:



          $data['pages']
          $data['posts']


          Then I realized that you hand over data to other objects and they might be using these two values. Who knows? This makes your code very hard to understand and to debug.



          Basically you're treating the $data array as a sort of object you hand over to other classes.



          But wait, did I say 'object'? But what if it was? Clearly you have a need to keep data accessible, but why use an array that you need to recreate every time? Why not use a class?



          Now I don't have any idea how your code is structure, and which class would be the best to use for this. But it would make sense to extend the basic CodeIgniter controller class to hold this data, like so:



          class Data_Controller extends CI_Controller 
          {
          private $data;

          public function __construct()
          {
          parent::__construct();
          $this->data = $this->Static_model->get_static_data();
          $this->data['pages'] = $this->Pages_model->get_pages();
          $this->data['categories'] = $this->Categories_model->get_categories();
          $this->data['posts'] = $this->Posts_model->sidebar_posts($limit=5, $offset=0);
          $this->data['page'] = $this->Pages_model->get_page($page_id);
          }


          public function getData()
          {
          return $this->data;
          }

          }


          or something to the same effect and then extend this for your pages class:



          class Pages extends Data_Controller {

          public function __construct()
          {
          // currently this whole method doesn't do anything, it can be removed
          parent::__construct();
          }

          public function page($page_id) {
          $data = $this->getData();
          ..........................

          }

          }


          And, of course, those controller classes that don't need all that data can just extend CI_Controller.



          I'm sure there are other ways of doing this. I don't like the fact that now you still collect all that information without actually knowning if it is needed. I would make the retrieval of the data dependent on the fact that it is actually used. In other words use getter methods, not a data array. I'll give an example for 'pages' and 'posts', but you have to create the other ones yourself:



          class Data_Controller extends CI_Controller 
          {

          public function getPages()
          {
          return $this->Pages_model->get_pages();
          }

          public function getCatagories()
          {
          return $this->Categories_model->get_categories();

          }

          }


          If you need to buffer the data you can do:



          class Data_Controller extends CI_Controller 
          {

          public function getCatagories()
          {
          static $buffer = NULL;
          if (is_null($buffer)) $buffer = $this->Categories_model->get_categories();
          return $buffer;
          }

          }


          Keep in mind that this buffer will work for all instances of Data_Controller. That can be an advantage, or a disadvantage.



          OK, that was a bit long. I hope you got some new ideas from my ramblings.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited 9 hours ago

























          answered 11 hours ago









          KIKO SoftwareKIKO Software

          1,679512




          1,679512

























              0












              $begingroup$

              In this case I would probably convert this $this->Static_model into a Config file that I can use through CI (that is what they are there for). You can even make CI load this file automatically, with hook. And you can even load different version based on your ENVIORMENT setting (for testing and what not).



              For the dynamic data, now depending how dynamic this is:



               $data['pages'] = $this->Pages_model->get_pages();


              I would probably use the Caching Driver. Chances are this doesn't update that much, and even when it does you can reset the cache. For example how often will you really add a new category. Certainly not every couple minutes, or even hours.



              One other thing not mentioned



              Avoid changing data types when returning from a method. You may not even realize you are doing it. In some cases its perfectly fine to return mixed data types, but as a general rule you should avoid it as it complicates your downstream code by having to check the return data all the time for it's type.



              I found this quick example (in your code):



              class Categories_model extends CI_Model {

              public function get_category($category_id){
              $query = $this->db->get_where('categories', array('id' => $category_id));
              if ($query->num_rows() > 0) {
              return $query->row();
              }

              } //<-- returns null || array

              }

              class Pages extends CI_Controller {
              public function page($page_id) {

              //...
              $data['categories'] = $this->Categories_model->get_categories(); //returns an array || null
              //...
              //requires a check (null is false, so is [])
              if ($data['categories']) {
              foreach ($data['categories'] as &$category) {
              $category->posts_count = $this->Posts_model->count_posts_in_category($category->id);
              }
              }
              //...
              }
              }


              Instead consider this:



              class Categories_model extends CI_Model {

              public function get_category($category_id){
              $query = $this->db->get_where('categories', array('id' => $category_id));
              if ($query->num_rows() > 0) {
              return $query->row();
              }
              return [];
              }

              }

              class Pages extends CI_Controller {
              public function page($page_id) {
              //...
              $data['categories'] = $this->Categories_model->get_categories(); //always returns an array
              //...
              //requires no type check, as an empty array simply skips the loop
              foreach ($data['categories'] as &$category) {
              $category->posts_count = $this->Posts_model->count_posts_in_category($category->id);
              }
              //...
              }
              }


              This may seem trivial, but it can add up to a lot of code. In PHP7 you can even set return type hints eg. public function get_category($category_id) : array. To insure the return type is consistent etc.



              Really when it comes to programing one of the most important things is consistency.



              Hope it helps!






              share|improve this answer











              $endgroup$


















                0












                $begingroup$

                In this case I would probably convert this $this->Static_model into a Config file that I can use through CI (that is what they are there for). You can even make CI load this file automatically, with hook. And you can even load different version based on your ENVIORMENT setting (for testing and what not).



                For the dynamic data, now depending how dynamic this is:



                 $data['pages'] = $this->Pages_model->get_pages();


                I would probably use the Caching Driver. Chances are this doesn't update that much, and even when it does you can reset the cache. For example how often will you really add a new category. Certainly not every couple minutes, or even hours.



                One other thing not mentioned



                Avoid changing data types when returning from a method. You may not even realize you are doing it. In some cases its perfectly fine to return mixed data types, but as a general rule you should avoid it as it complicates your downstream code by having to check the return data all the time for it's type.



                I found this quick example (in your code):



                class Categories_model extends CI_Model {

                public function get_category($category_id){
                $query = $this->db->get_where('categories', array('id' => $category_id));
                if ($query->num_rows() > 0) {
                return $query->row();
                }

                } //<-- returns null || array

                }

                class Pages extends CI_Controller {
                public function page($page_id) {

                //...
                $data['categories'] = $this->Categories_model->get_categories(); //returns an array || null
                //...
                //requires a check (null is false, so is [])
                if ($data['categories']) {
                foreach ($data['categories'] as &$category) {
                $category->posts_count = $this->Posts_model->count_posts_in_category($category->id);
                }
                }
                //...
                }
                }


                Instead consider this:



                class Categories_model extends CI_Model {

                public function get_category($category_id){
                $query = $this->db->get_where('categories', array('id' => $category_id));
                if ($query->num_rows() > 0) {
                return $query->row();
                }
                return [];
                }

                }

                class Pages extends CI_Controller {
                public function page($page_id) {
                //...
                $data['categories'] = $this->Categories_model->get_categories(); //always returns an array
                //...
                //requires no type check, as an empty array simply skips the loop
                foreach ($data['categories'] as &$category) {
                $category->posts_count = $this->Posts_model->count_posts_in_category($category->id);
                }
                //...
                }
                }


                This may seem trivial, but it can add up to a lot of code. In PHP7 you can even set return type hints eg. public function get_category($category_id) : array. To insure the return type is consistent etc.



                Really when it comes to programing one of the most important things is consistency.



                Hope it helps!






                share|improve this answer











                $endgroup$
















                  0












                  0








                  0





                  $begingroup$

                  In this case I would probably convert this $this->Static_model into a Config file that I can use through CI (that is what they are there for). You can even make CI load this file automatically, with hook. And you can even load different version based on your ENVIORMENT setting (for testing and what not).



                  For the dynamic data, now depending how dynamic this is:



                   $data['pages'] = $this->Pages_model->get_pages();


                  I would probably use the Caching Driver. Chances are this doesn't update that much, and even when it does you can reset the cache. For example how often will you really add a new category. Certainly not every couple minutes, or even hours.



                  One other thing not mentioned



                  Avoid changing data types when returning from a method. You may not even realize you are doing it. In some cases its perfectly fine to return mixed data types, but as a general rule you should avoid it as it complicates your downstream code by having to check the return data all the time for it's type.



                  I found this quick example (in your code):



                  class Categories_model extends CI_Model {

                  public function get_category($category_id){
                  $query = $this->db->get_where('categories', array('id' => $category_id));
                  if ($query->num_rows() > 0) {
                  return $query->row();
                  }

                  } //<-- returns null || array

                  }

                  class Pages extends CI_Controller {
                  public function page($page_id) {

                  //...
                  $data['categories'] = $this->Categories_model->get_categories(); //returns an array || null
                  //...
                  //requires a check (null is false, so is [])
                  if ($data['categories']) {
                  foreach ($data['categories'] as &$category) {
                  $category->posts_count = $this->Posts_model->count_posts_in_category($category->id);
                  }
                  }
                  //...
                  }
                  }


                  Instead consider this:



                  class Categories_model extends CI_Model {

                  public function get_category($category_id){
                  $query = $this->db->get_where('categories', array('id' => $category_id));
                  if ($query->num_rows() > 0) {
                  return $query->row();
                  }
                  return [];
                  }

                  }

                  class Pages extends CI_Controller {
                  public function page($page_id) {
                  //...
                  $data['categories'] = $this->Categories_model->get_categories(); //always returns an array
                  //...
                  //requires no type check, as an empty array simply skips the loop
                  foreach ($data['categories'] as &$category) {
                  $category->posts_count = $this->Posts_model->count_posts_in_category($category->id);
                  }
                  //...
                  }
                  }


                  This may seem trivial, but it can add up to a lot of code. In PHP7 you can even set return type hints eg. public function get_category($category_id) : array. To insure the return type is consistent etc.



                  Really when it comes to programing one of the most important things is consistency.



                  Hope it helps!






                  share|improve this answer











                  $endgroup$



                  In this case I would probably convert this $this->Static_model into a Config file that I can use through CI (that is what they are there for). You can even make CI load this file automatically, with hook. And you can even load different version based on your ENVIORMENT setting (for testing and what not).



                  For the dynamic data, now depending how dynamic this is:



                   $data['pages'] = $this->Pages_model->get_pages();


                  I would probably use the Caching Driver. Chances are this doesn't update that much, and even when it does you can reset the cache. For example how often will you really add a new category. Certainly not every couple minutes, or even hours.



                  One other thing not mentioned



                  Avoid changing data types when returning from a method. You may not even realize you are doing it. In some cases its perfectly fine to return mixed data types, but as a general rule you should avoid it as it complicates your downstream code by having to check the return data all the time for it's type.



                  I found this quick example (in your code):



                  class Categories_model extends CI_Model {

                  public function get_category($category_id){
                  $query = $this->db->get_where('categories', array('id' => $category_id));
                  if ($query->num_rows() > 0) {
                  return $query->row();
                  }

                  } //<-- returns null || array

                  }

                  class Pages extends CI_Controller {
                  public function page($page_id) {

                  //...
                  $data['categories'] = $this->Categories_model->get_categories(); //returns an array || null
                  //...
                  //requires a check (null is false, so is [])
                  if ($data['categories']) {
                  foreach ($data['categories'] as &$category) {
                  $category->posts_count = $this->Posts_model->count_posts_in_category($category->id);
                  }
                  }
                  //...
                  }
                  }


                  Instead consider this:



                  class Categories_model extends CI_Model {

                  public function get_category($category_id){
                  $query = $this->db->get_where('categories', array('id' => $category_id));
                  if ($query->num_rows() > 0) {
                  return $query->row();
                  }
                  return [];
                  }

                  }

                  class Pages extends CI_Controller {
                  public function page($page_id) {
                  //...
                  $data['categories'] = $this->Categories_model->get_categories(); //always returns an array
                  //...
                  //requires no type check, as an empty array simply skips the loop
                  foreach ($data['categories'] as &$category) {
                  $category->posts_count = $this->Posts_model->count_posts_in_category($category->id);
                  }
                  //...
                  }
                  }


                  This may seem trivial, but it can add up to a lot of code. In PHP7 you can even set return type hints eg. public function get_category($category_id) : array. To insure the return type is consistent etc.



                  Really when it comes to programing one of the most important things is consistency.



                  Hope it helps!







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited 8 hours ago

























                  answered 9 hours ago









                  ArtisticPhoenixArtisticPhoenix

                  45128




                  45128






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Code Review Stack Exchange!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      Use MathJax to format equations. MathJax reference.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f217002%2fcodeigniter-3-how-can-i-avoid-repeating-this-chunk-of-code-in-my-controllers%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Fairchild Swearingen Metro Inhaltsverzeichnis Geschichte | Innenausstattung | Nutzung | Zwischenfälle...

                      Pilgersdorf Inhaltsverzeichnis Geografie | Geschichte | Bevölkerungsentwicklung | Politik | Kultur...

                      Marineschifffahrtleitung Inhaltsverzeichnis Geschichte | Heutige Organisation der NATO | Nationale und...