How to auto include to use own class with CodeIgniter - codeigniter

I am using CodeIgniter. I want to use my own class to pass as an argument inside controller functions.
Normally, I can put this class in a folder and include it to MY_Controller with its path. But I want to learn if there is a way to do this in CodeIgniter. I can't put it in libraries folder and can't use loader class because it tries to create an instance of an object, but I want to create instance whenever I want. Loader class gives an error if my own class need constructor parameters.
What is the best way to do that?
Which is the best folder to put in it?

This is very easy. Consider this example
<?php
Class Home extends CI_Controller{
public $arg1 = 1;
public $arg2 = 2;
function index($this->$arg1 , $this->$arg2){ //or function index()
//Then inside function
//$vara = $this->$arg1 , $varb = $this->$arg2;
}
}

Related

How import custom class in controller Laravel?

I have created a new directory Library in root of Laravel.
Inside I put the file with class:
class My {
//
}
So, in controller Laravel I try to get access to this class:
App\Library\My
But Laravel does not determine this path.
This is my code:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use View;
use App\Library\My;
class HomeController extends Controller
{
//
}
A complete and functional example based on the posts here:
1 - Folder and file - Create a folder under app/, in this example we will create a folder called Library.
We will also inside the folder create a file with the name of your class, here we will create a class called My.
So we will have app/Library/My.php
2 - Class and method - Now, for testing, inside the class create a static method called myMethod
<?php
namespace App\Library;
class My
{
public static function myMethod()
{
return 'it\'s work!';
}
}
3 - Controller - Now at the beginning of the Controller, we will declare the namespace of your Class with use:
<?php
namespace App\Http\Controllers;
use App\Library\My;
//rest of the controller code
Finally, to create an instance of the My class, in Controller, a new statement must be used:
//rest of the controller code
public function index()
{
$whatever = new My;
return $whatever::myMethod();
}
As above, make sure it is placed in the App directory and make sure it is properly namespaced e.g.
<?php
$fOne = new \App\library\functions;
$isOk = ($fOne->isOk());
?>
You should create Library folder inside app folder
namespace App\Library\My
app folder is alrdy used psr-4
In your controller
use App\Library\My as My
It's work for me. Hope this answer is helpful
You have to properly namespace your every class.
So you can import your class with use keyword, like so
use App\Library\My;
....
$my = new My();
Or if you've conflicting class name then you can use as keyword to alias the classname while importing
use App\Library\My as MySecond;
....
$my = new MySecond();
And if you want to directly access your class within the method then you can access it like so.
$my = new \App\Library\My();
Note: The leading \ means App was declared in the global scope.

CodeIgniter: How to load my own class of static functions into a controller?

I have a class of static functions (common utility functions) that I wish to load into codeigniter. Currently I am loading it normally using an include_once(...) and it works as expected.
However, I want to load it using codeigniter's methodology. I understand that I should save my class file into the third_party directory; and that I should create a library class (saving it in the library directory) which requires my class.
Below are the three components, but it does not work.
1
// my class, saved at: APPPATH.'third_party/My_Class.php'
class My_Class
{
public static function my_static_utility_method ( )
{
return "booger" ;
}
// ...
}
2 - I understand that I am supposed to create a wrapper that obeys the CI rules of 'library' instantiation:
// saved at: APPPATH.'libraries/Library_Wrapper.php'
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Library_Wrapper
{
public function __construct()
{
require_once APPPATH.'third_party/My_Class.php';
}
}
3 - Now I want to access the static methods of My_Class from my controller:
// saved at: APPPATH.'controllers/my_controller.php'
class My_Controller extends CI_Controller
{
public function __constructor( )
{
parent::__construct();
$this->load->library( 'Library_Wrapper' ) ;
}
public function some_function()
{
echo $this->My_Class->my_static_utility_method( ) ;
}
}
Try the following steps:
Create a new controller file: application/core/MY_Controller.php. In that file you may add your static functions.
<?php
class MY_Controller extends CI_Controller {
protected function static_fn1() {
//code
}
}
The controllers which need to access the static functions may extend this class like:
File: application/controllers/Welcome.php :
<?php
class Welcome extends MY_Controller {
public function fnname() {
//code
}
}
You've almost got the 3rd step in place but not quite. Loading the library will take the same name that you loaded it with:
//Load library
$this->load->library( 'Some_name' );
//Use Library
$this->some_name->someFunction();
So in your case, you'd need to switch method which accesses the library from:
//Will throw an PHP undefined My_Class error
echo $this->My_Class->my_static_utility_method();
to Library_wrapper instead:
//from $this->load->library( 'Library_wrapper' );
echo $this->library_wrapper->my_static_utility_method();
But this presents the next problem as My_Class is a property of library_wrapper so calling it gets a bit lengthy:
echo $this->library_wrapper->My_Class->my_static_utility_method();
Which should successfully call the My_Class descendent methods if publicly accessible.
This isn't clean as you would perfer. It would better to extend My_Class into Library_wrapper instead to share the static instances:
/**
* Static helper methods:
**/
class Library_wrapper extends My_Class {
}
It is possible to bind the 'load' the library to a different name (See "Assigning a Library to a different object name" header).
You can try the solution below:
in this hierarchy $this->library_wrapper->My_Class->my_static_utility_method();
use the php function listed at Php Functions to find out the methods/variables at each point in the hierarchy. This will pin point to the exact location where the things are going wrong.
I do NOT think you need to construct a class. The easiest way would be a helper ("Helpers, as the name suggests, help you with tasks. Each helper file is simply a collection of functions in a particular category" - just read the article from the official tutorial).
Your helper file with a name like myfunctions_helper.php will be located into /application/helpers folder and could have a structure like this:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
if (!function_exists('my_static_fuction')) {
function my_static_fuction ( )
{
return "booger" ;
}
}
// etc...
Then you can autoload the helper declaring it to the /application/config/autoload.php.
$autoload['helper'] = array('url','myfunctions');
If you need to construct a class then a library like #MackieeE wrote will do the job (check the tutorial for more info).

Access an object of one class in other codeigniter

I have two controller classes in my codeigniter application, say class A and B.I just want to create an object of class A and access the functions declared in class A from class B.Something like:-
class A extends someclass
{
public function function1(){
$this->load->view('welcome_message');
}
}
}
class B extends someclass2
{
protected $object;
public function __construct()
{
parent::__construct();
$this->objectA = new A();
}
}
}
I want to access the function function1 from class B using the object objectA. How can i do this?
Please help.
Thanks
well actually this is not the proper way in codeigniter. Actually when you have common functions in and you want to use them in 2 or more controllers. The best way is to create base controller in core folder with name of MY_Contoller and extend it from CI_Contoller. Write your common function in MY_Contoller. Now you have to extend all your controllers from MY_Contoller instead of CI_Contoller. You can do the same with Model.
Cross-controller access goes against CI best practice.
Either inherit both controllers from a controller that holds this common functionality (don't forget to prefix the function with '_' so it's inaccessible via url routing) or create a library that contains your re-usable functionality. A helper can also work.

Call a controller from a method

Can we call a controller and parsing any values or data to the controller from a method?
let's say that i have this method,
function loader(){
//some operations to call another controller
}
and from that method i want to call a controller named welcome.php wich is located in /application/controller
i'v tried this but it doesn't work
function loader(){
$open = new Welcome();
}
it says that Class Welcome not found
Sorry for my bad english
At first You have to include the file
include('welcome.php');
Then, create the object.
function loader(){
$open = new welcome();
//if you want to call a method in an object
$open->MyWelcomeMethod();
}
Makesure that your loader controller was extended to welcome controller.
Suppose controller welcome,my_controller are two controller and loader function in B then
class Welcome extends CI_Controller {
function my_fun() {}
}
then you can call my_fun() when you are entended from my_controller like
class My_Controller extends Welcome {
$open = $this->my_fun();
}

default language codeigniter

i want to run this code at the first of all my webpages,
I'm using codeigniter
the code is:
if(!$this->session->userdata('lang')):
$this->session->set_userdata('lang','ar');
endif;
how to do that?
If you haven't already, it may be worth looking at CodeIgniter's language class.
You can extend the native CI_Controller class. Extending this class allows you to add your additional functionality, while the original functionality of the native core class remains.
For the code to run first on all pages, you can add your code to the constructor of the newly created subclass - if you extend your controller(s) with the new subclass, then this code will be run when any function in your controller(s) is called. To do this:
Create a subclass
Create a file named MY_Controller.php in the application/core/ directory of your project. This new class needs to extend CI_Controller and the parent constructor. The class should look something like this:
<?php
class MY_Controller extends CI_Controller {
public function __construct()
{
parent::__construct(); //make sure you extend the parent constructor
//Your code:
if( ! $this->session->userdata('lang') )
$this->session->set_userdata('lang','ar');
}
}
Ensure the class prefix is correct
If you've used MY_ as the prefix for the new class then you shouldn't need to do anything here, but it's useful to know anyway.
You'll also need to ensure that the sub-class prefix is set correctly in the application/config/config.php file.
$config['subclass_prefix'] = 'MY_';
This prefix must match the prefix of the new class that you create. By default it is MY_ but you can change it to what you want as long as they correspond - FOO_, BAR_, WHATEVER_... The exception is CI_, which is reserved for CodeIgniter's native libraries.
Extend all of you application's controller with the new subclass
Your controller(s) in application/controllers/ is(/are) probably extending CI_Controller. To make use of the newly created subclass, your controller should extend MY_Controller and the parent constructor.
class Welcome extends MY_Controller {
function __construct()
{
parent::__construct();
}
//More functions...
}

Resources