how to create a contruct() in codeigniter4 controller? - php

class Home extends BaseController
{
var $cache;
public function __contruct()
{
parent::__construct();
$this->cache = \Config\Services::cache();
}
public function reset()
{
$this->cache->clean();
}
}
assume i have create a web cache.
the idea is i dont want to keep assign the same $cache in every method.
So contructor should do the job.
but when i load the page, it shows -> Undefined variable: cache
how to fix my code/this issue?

class Home extends \CodeIgniter\Controller
{
public function __construct(...$params)
{
parent::__construct(...$params);
// Your own constructor code
}
}

looks like codeigniter have already created a constructor method in the BaseController.
Therefore, i just load the function that i wish to preload/initialized in that BaseController.php.
Fixed.

Related

Initialize function to run once only

I'm inside a Laravel controller. I only want the init() method to fire once. What actually happens is, it fires every time I run the controller/methods via a browser?
class MyController extends Controller
{
public function __construct()
{
static $init_called = false;
if(!$init_called){
$init_called = true;
$this->init();
}
}
public function init()
{
// initialize code here, execute 'once' only
}
public function routeOne(){}
public function routeTwo(){}
}
One solution is to store a value on session or on database. This value allow you to know if the function has already been called.
Then check the value at the top of the method every time it's is fired.
if it's true you can proceed to the normal instructions else you exit the function.
Since Http is a stateless protocol I'm probably attempting something outside of the realms of possibility. As a workaround, I used the following:-
// Call this route once only
Route::get('/init', [MyController::class, 'init'])->name('initialize');
class MyController extends Controller
{
public function init()
{
MyModel::persistData();
}
}
class MyModel extends Model
{
private $data;
public static function persistData()
{
$data = ['some data'];
MyModel::insert($data);
}
}

Access an array in all views in codeigniter

I made an array in MY_Controller class placed on core folder. In its constructor i fetched records from db so as to make navigation menu in my views. Since i have different page layouts so i cannot call the same header view every where. for this reason i made a core class as per my understanding which i am not sure is right or not. below is the code for my controller
class MY_controller extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('Category_model');
$data['parent'] = $this->Category_model->getParentCategories();
$data['child'] = $this->Category_model->getChildCategories();
}
}
my default controller is main
class Main extends MY_controller {
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->load->view('home/header',$data);
$this->load->view('home/footer');
}
Now in my header view i am receiving undefined variable parent and child error. I want this two variables available in all the views so that i do not have to define those two variables in every controller.
Thanks
You may try something like this:
class MY_controller extends CI_Controller
{
$commonData = array();
function __construct()
{
parent::__construct();
$this->load->model('Category_model');
$this->commonData['parent'] = $this->Category_model->getParentCategories();
$this->commonData['child'] = $this->Category_model->getChildCategories();
}
}
Then use $this->comonData in your index method instead of $data to pass to the view:
public function index()
{
$this->load->view('home/header', $this->comonData);
$this->load->view('home/footer');
}
Now it'll be available in the header view and since it's at the top of other views then you may use it further, unless you override it with other value in any class.

codeigniter declaring a class in to one variable

i am trying to use $admin->function() instead $this->admin_model->function()
when i tried to declare a variable $admin=new Admin_model; in constructor and use it in other functions it gives error..
my code is given below, i don't know much about OOP concept, somebody please help.
class Admin extends CI_Controller {
var $admin;
function __construct() {
parent::__construct();
$this->load->model('admin_model');
$admin=new Admin_model;
}
public function index($value='')
{
if(!$admin->is_admin_logged_in()){
redirect('admin/login?r='.urlencode(current_url()));
}
$data['loggedin']=TRUE;
$data['account']=$this->session->all_userdata();
$this->load->view('pages/admin-home',isset($data)?$data:NULL);
}
}
presently i am using this method
public function login()// this function belongs to the same controller mentioned above
{
$r=isset($_GET['r'])?urldecode($_GET['r']):'admin';
$admin=new Admin_model;
if($admin->is_admin_logged_in()) redirect($r);
}
i don't want declare $admin=new Admin_model; in every single function and want to make the code look good and clean, so don't like to use $this->admin or $this->admin_model either.
You are trying to give an alias to a model (as what I can see)
All you have to do is:
class Admin extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('admin_model', 'admin');
}
public function index($value='')
{
if(!$this->admin->is_admin_logged_in()){
redirect('admin/login?r='.urlencode(current_url()));
}
$data['loggedin']=TRUE;
$data['account']=$this->session->all_userdata();
$this->load->view('pages/admin-home',isset($data)?$data:NULL);
}
}
Notice where the alias of the model is given
$this->load->model('admin_model', 'admin');
And how it is used
if(!$this->admin->is_admin_logged_in()){

What is the correct way to access a model in an controller on Laravel

I'm new on Laravel 4 and I am trying to understand it.
is searched on google and on stackoverflow. Maybe i am not searching for the right syntax but i hope someone can help me, with it.
In CodeIgniter i understand it (probably). There I use in an Controller:
function __construct()
{ $this->load->model('example_m'); }
But how about in Laravel 4?
I figured out the following:
i make a static function in de model so i can access it everywhere. Example:
class Example extends Eloquent // this is the model
{
public static function TestExample(){
// do some stuff here
}
}
Or i could do it like this:
class ExampleController extends BaseController
{
public $test = null;
public function __construct()
{
$this->test = new Example();
}
public function index()
{
$this->test->TestExample();
}
}
My question is: Is there an other way and/or what is the correct way?
http://four.laravel.com/docs/ioc
App::bind('ExampleModelInterface', 'Example');
class ExampleController extends BaseController {
public function __construct(ExampleModelInterface $model)
{
$this->model = $model;
}
}
Do you mean simply accessing the method of a model?
Since they are static you use: Modell::method()
You might have to do a composer dump-autoload though so L4 autoloads it correctly.

Can't access property in abstract class via sub class

I am trying to build an abstract base controller that will extend all other controllers. So far I have something like:
abstract class BaseController {
protected $view;
protected $user;
public function __construct() {
$this->view = new View; //So a view is accessible to subclasses via $this->view->set();
$this->user = new User; //So I can check $this->user->hasPermission('is_admin');
}
abstract function index();
}
class UserController extends BaseController {
public function index() {}
public function login() {
if($this->user->isLoggedin()) {
redirect to my account
}
else {
$this->view->set('page_title', "User Login");
$this->view->set('sidebar', $sidebar); //contains sidebar HTML
$this->view->set('content', $content); //build main page HTML
$this->view->render();
}
}
}
The problem i get is I get errors like this:
Call to a member function set() on a non-object in C:\xampp\htdocs\program\core\controllers\admin.controller.php on line 44
If I put the $user and $views properties in the main controller (ie UserController), everything works fine. But I only want to set up these objects once (in the base controller) and not have to add $this->view = new View; in all my controllers.
FIXED: I overrode my constructors and I thought you couldn't call parent::__construct() on abstract classes.
What you are trying to do should work. Make sure you aren't covering up your constructor in UserController. (i.e., if it has a constructor, it needs to call its parent constructor.)
Otherwise, do some debugging to see where $this->view is being reset.
Your code works for me. You are either overriding your __construct() method in UserController, or you are overridding the view field with something other than a View object.
What you have in this form would work.

Categories