1

I have more function where I need to read $data['getContacts'] more times, the code working correctly, but there is a clean and different method for call it?

thanks!

 class AppController extends CI_Controller {

        public $id;

        function __construct() {

           parent::__construct(); 

           $this->id =  !empty($this->input->post('id')) ? (int)$this->input->post('id', TRUE) : '';             

        }

           public function restoreCredit()
           {

               $data['getContacts'] = $this->appmodel->getContacts($this->id); //repeat here?

           if($data['getContacts']->status != false) :

                     $this->appmodel->restoreCredit($this->id);

           endif; 

           }

            public function createRandToken()
            {
                $data['getContacts'] = $this->appmodel->getContacts($this->id); //repeat here?
                    if(!empty($data['getContacts']) && $data['getContacts']->token == false): 

                      $this->appmodel->setRandUserToken($this->id);

                endif;  
            }

    }

1 Answer 1

1

Your could define a function getContacts. It will fetch $contacts first time from the DB, after that it will always returned the fetched Contacts.

<?php
class AppController extends CI_Controller
{

    public $id;
    public $contacts;

    function __construct()
    {

        parent::__construct();

        $this->id = !empty($this->input->post('id')) ? (int) $this->input->post('id', TRUE) : '';
    }

    public function getContacts() {

        if( !empty ( $this->contacts) ) { //If its populated return from here.
            return $this->contacts;
        }

        $this->contacts = $this->appmodel->getContacts($this->id);
        return $this->contacts;
    }

    public function restoreCredit()
    {

        $data['getContacts'] = $this->getContacts();

        if ($data['getContacts']->status != false) :

            $this->appmodel->restoreCredit($this->id);

        endif;
    }

    public function createRandToken()
    {
        $data['getContacts'] = $this->getContacts();
        if (!empty($data['getContacts']) && $data['getContacts']->token == false) :

            $this->appmodel->setRandUserToken($this->id);

        endif;
    }
}

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, because there are changes in 2 functions and a new function has been created.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.