I am using codeigniter 3
in application/config/config.php file I have added this autoload code for model
function __autoload($class) {
if (file_exists(APPPATH."models/".strtolower($class).EXT)) {
include_once(APPPATH."models/".strtolower($class).EXT);
}
}
to autoload model
and I am using model in controller like this
public function index()
{
$post = new post();
}
but it is showing error
Class 'post' not found
I do have post model in model folder already created
I am using the autoload code from source
http://code.tutsplus.com/tutorials/6-codeigniter-hacks-for-the-masters--net-8308
but it is not working like shown in blog.
Do I need anything else to update more for this?
If you need to autoload a model in your CI3 app, just go in application/config/autoload.php and find the line :
$autoload['model'] = array();
Then, add the model you want to autoload :
$autoload['model'] = array('my_model', 'my_second_model');
Then in your controller, you don't need to create a new instance of your model class. Example :
$res = $this->my_model->myfunction();
Use capital letter for your class name.
Btw. I agree with first answer.
Related
I have two controller file homecontroller and backendcontroller. What is the best way to create global function and access it from both files?
I found here Arian Acosta's answer helpful but I wonder if there is an easiest way. I would appreciate any suggestions.
Solution
One way to do this is to create a class and use its instance, this way you can not only access the object of the class within a controller, blade, or any other class as well.
AppHelper file
In you app folder create a folder named Helpers and within it create a file name AppHelper or any of your choice
<?php
namespace App\Helpers;
class AppHelper
{
public function bladeHelper($someValue)
{
return "increment $someValue";
}
public function startQueryLog()
{
\DB::enableQueryLog();
}
public function showQueries()
{
dd(\DB::getQueryLog());
}
public static function instance()
{
return new AppHelper();
}
}
Usage
In a controller
When in a controller you can call the various functions
public function index()
{
//some code
//need to debug query
\App\Helpers\AppHelper::instance()->startQueryLog();
//some code that executes queries
\App\Helpers\AppHelper::instance()->showQueries();
}
In a blade file
Say you were in a blade file, here is how you can call the app blade helper function
some html code
{{ \App\Helpers\AppHelper::instance()->bladeHelper($value) }}
and then some html code
Reduce the overhead of namespace (Optional)
You can also reduce the overhead of call the complete function namespace \App\Helpers by creating alias for the AppHelper class in config\app.php
'aliases' => [
....
'AppHelper' => App\Helpers\AppHelper::class
]
and in your controller or your blade file, you can directly call
\AppHelper::instance()->functioName();
Easy Solution:
Create a new Helpers folder in your app directory.
Create a php file named your_helper_function.php in that Helpers directory.
Add your function(s) inside your_helper_function.php
function your_function($parameters){
//function logic
}
function your_another_function($parameters){
//function logic
}
Add this file to the Files key of your composer.json like
"autoload": {
...
"files": [
"app/Helpers/your_helper_function.php"
]
...
}
Finally, regenerate composer autoload files. (Run this in your project directory)
composer dump-autoload
That's it! and now you can access your_function() or your_another_function() in any part of your Laravel project.
If you still have any confusion, check my blog post on how to do this:
How to Add a Global Function in Laravel Using Composer?
Updated:
Step 1
Add folder inside app folder
app->Helper
Step 2
add php Class inside Helper folder
Eg. Helper.php
Add namespace and class to the Helper.php
namespace App\Helper;
class Helper
{
}
Register this Helper.php into config/app.php file
'aliases' => [
....
'Helper' => App\Helper\Helper::class
]
Now, write all the functions inside Helper.php and it will be accessible everywhere.
How to access from Controller?
Step 1 - Add a namespace at top of the controller.
use App\Helper\Helper;
Step 2 - Call function - Assume there a getInformation() inside the Helper Class.
$information = Helper::getInformation()
In your Controller.php which extends BaseController, you can create a function like;
public function data($arr = false)
{
$data['foo'] = 'bar';
return array_merge($data,$arr);
}
And from any controller when you send a data to a view;
public function example()
{
$data['smthg'] = 'smthgelse';
return view('myView',$this->data($data));
}
The data in the the main controller can be accessed from all controllers and blades.
The Laravel Service Provider way
I've been using global function within Laravel for a while and I want to share how I do it. It's kind of a mix between 2 answers in this post : https://stackoverflow.com/a/44021966/5543999 and https://stackoverflow.com/a/44024328/5543999
This way will load a file within a ServiceProvider and register it within your Laravel app.
Where is the difference, the scope, it's always about the scope.
Composer //Autload whitin composer.json method
|
|--->Laravel App //My method
|
|--->Controller //Trait method
|--->Blade //Trait method
|--->Listener //Trait method
|--->...
This is a really simplist way to explain my point, all three methods will achieve the purpose of the "Global function". The Traits method will need you to declare use App\Helpers\Trait; or App\Helpers\Trait::function().
The composer and service provider are almost about the same. For me, they answer better to the question of what is a global function, because they don't require to declare them on each place you want to use them. You just use them function(). The main difference is how you prefer things.
How to
Create the functions file : App\Functions\GlobalFunctions.php
//App\Functions\GlobalFunctions.php
<?php
function first_function()
{
//function logic
}
function second_function()
{
//function logic
}
Create a ServiceProvider:
//Into the console
php artisan make:provider GlobalFunctionsServiceProvider
Open the new file App\Providers\GlobalFunctionsServiceProvider.php and edit the register method
//App\Providers\GlobalFunctionsServiceProvider.php
public function register()
{
require_once base_path().'/app/Functions/GlobalFunctions.php';
}
Register your provider into App\Config\App.php wihtin the providers
//App\Config\App.php
'providers' => [
/*
* Laravel Framework Service Providers...
*/
Illuminate\Auth\AuthServiceProvider::class,
...
Illuminate\Validation\ValidationServiceProvider::class,
Illuminate\View\ViewServiceProvider::class,
App\Providers\GlobalFunctionsServiceProvider::class, //Add your service provider
Run some artisan's commands
//Into the console
php artisan clear-compiled
php artisan config:cache
Use your new global functions
//Use your function anywhere within your Laravel app
first_function();
second_function();
Laravel uses namespaces by default. So you need to follow the method described in that answer to setup a helper file.
Though in your case you want to access a method in different controllers. For this there's a simpler way. Add a method to you base controller app/Http/Controllers/Controller.php and you can access them in every other controller since they extend it.
// in app/Http/Controllers/Controller.php
protected function dummy()
{
return 'dummy';
}
// in homecontroller
$this->dummy();
There are a few ways, depending on the exact functionality you're trying to add.
1) Create a function inside Controller.php, and make all other controller extend that controller. You could somewhat compair this to the master.blade.php
2) Create a trait, a trait can do a lot for you, and keeping ur controllers clean. I personally love to use traits as it will look clean, keep my Controller.php from being a mess with tons of different lines of code.
Creating a global function
create a Helpers.php file under a folder, let's name it 'core'.
core
|
-- Helpers.php
namespace Helpers; // define Helper scope
if(!function_exists('html')) {
function html($string) {
// run some code
return $str;
}
}
In your composer.json
"autoload": {
"psr-4": {
},
"files": [
"core/Helpers.php"
]
}
in the file that you want to use it
// the " use " statement is not needed, core/Helpers is loaded on every page
if(condition_is_true) {
echo Helpers\html($string);die();
}
Remove the namespace in Helpers.php if you want to call your function without the need to prefix namespace. However I advise to leave it there.
Credit: https://dev.to/kingsconsult/how-to-create-laravel-8-helpers-function-global-function-d8n
By using composer.json and put the function containing file(globalhelper.php) to the autoload > files section, then run
composer dump-autoload
You can access the function inside the file(globalhelper.php) without having to calling the class name, just like using default php function.
I am trying to add controller view in my existing project that consider model view controller structure in php with laravel.
class CashFlowdataController extends Controller {
public function index() {
return view('CashFlowdata::create');
}
}
When I implement this, it shows me error for,
InvalidArgumentException
No hint path defined for [CashFlowdata].
I have added file in route.php and web.php as added other controller data. Only for this one it shows message like this.
you code is wrong you should to something like this
class CashFlowdataController extends Controller {
public function index() {
return view('CashFlowdata.create');
}
}
here CashFlowdata.create
its means in laravel
folder structure should be
view>CashFlowdata>create.blade.php
laravel view() function is a helper to load view file
ref link https://laravel.com/docs/8.x/helpers#method-view
I had the same issue in nwidart/laravel-modules due to module.json file was miss place.
I move the file to the root of module now working fine.
When I manually load models in codeigniter I can specify an alias like so:
$this->load->model("user_model","user"); //user is an alias to user_model
$this->user->getProfile(); //use the alias to refer to the actual model
Some of these models are being extensively used in my application and so I decided to autoload them using autoload.php. I know I can load them so:
$autoload['model'] = array("user_model","another_model");
However they are referenced all over with their aliases. I want to load them with existing alias name so that the current code is not disturbed.
I guess I can have some code like this in an autoloaded helper maybe:
$ci= &get_instance();
$ci->user = $ci->user_model;
But what I wanted to check is, can I load model with alias name while autoloading?
yes you can create same alias in in autoload pass as an array try but not possiable with only alias you can create same alias as auto loading time.
$autoload['model'] = array(array('users_model', 'users'), array('an_model', 'an'), 'other_model');
or try
$autoload['model'] = array(array('users_model', 'users', FALSE));
For more :- https://github.com/EllisLab/CodeIgniter/issues/2117
http://ellislab.com/forums/viewthread/110977/#560168
For CodeIgniter 2.x this is not possible in autoloading, but you can do it by extending the default controller. Create a file MY_Controller.php in the application/core directory, with this code:
<?php
class MY_Controller extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('Example_model', 'alias');
}
}
Of course, replace Example_model and alias with your appropriate model and desired alias.
Then change your controllers to extend MY_Controller instead of CI_Controller. Now you can use $this->alias->whatever() in any Controller.
I have set up a project with CodeIgniter 2.1 and Doctrine 2.2, following the instruction on
Doctrine cookbook. The EntityManager works, but when I try to load entity models, it
gives me error
Fatal error: Class 'Users' not found in /Volumes/Data/Projects/myproject/application/controllers/home.php on line 10
This is my home.php file:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
//require_once(APPPATH.'models/Users.php');
class Home extends CI_Controller {
public function index()
{
$em = $this->doctrine->em;
$users = new Users;
//$user = $em->find("Users", 1);
$em->flush(); // dummy
$this->load->view('welcome_message');
}
}
If I uncomment line 3: require_once(APPPATH.'models/Users.php');, then
it works perfectly.
How can I make the models auto-loaded?
Is the autoload mechanism handled by the bootstrap in libraries/ Doctrine.php, isn't it?
$entitiesClassLoader = new ClassLoader('models', rtrim(APPPATH, "/" ));
$entitiesClassLoader->register();
Please anyone give me insight about this issue.
I'm guessing that you have a namespace line inside of your Users.php file?
If so then you will need to add a "use" statement to your controller code so the php namespace system knows where to look for your entities.
If not then verify that your entitiesClassLoader is actually being called and that APPPATH has the expected value.
I've never worked with CI and Doctrine so don't know if Doctrine should load the models or where it loads them, but you should try to do it yourselft, not with an include but this way :
In the Controller :
$this->load->model('Users');
Or as Autoload in application/config/autoload.php and load the model in the Array.
I created a few files in app/Lib folder and would like to access one of my models from the library classes:
<?php
App::uses('CrawlerBase','Lib');
App::uses('Deal', 'Model');
class SampleCrawler extends CrawlerBase {
public $uses = array('Deal');
function __construct(){
$this->Deal->create();
However, cake cant seems to find the Deal model and im getting a call to member function create() on a non-object in the model creation line.
Appreciate the help.
Always include models manually if not in a controller/shell:
$this->Deal = ClassRegistry::init('Deal');
and then
$this->Deal->create(); // etc
The advantage: You let Cake load and init the model for you, so if you already did that earlier it will try to reuse it.
EDIT: for the sake of completeness, inside a controller/shell you can simply do
$this->loadModel('Deal');
$this->Deal->create();
Other way to also do this:
APP::import('Model', 'Deal');
$this->Deal = new Deal();
$this->Deal->create();
Try;
$deal = new Deal(); // to create Deal Object
//if that doesnot work then, do
ClassRegistry::init("Deal");
$deal = new Deal();