Call a method from one controller inside another - laravel

Is it possible to call a method from one controller inside another controller in Laravel 5 (regardless the http method used to access each method)?

This is how I have done it. Use the use keyword to make the OtherController available. Then you can call a method from that class on instantiation.
<?php namespace App\Http\Controllers;
use App\Http\Controllers\OtherController;
class MyController extends Controller {
public function __construct()
{
//Calling a method that is from the OtherController
$result = (new OtherController)->method();
}
}
Also check out the concept of a Command in Laravel. It might give you more flexibility than the method above.

use App\Http\Controllers\TargetsController;
// this controller contains a function to call
class OrganizationController extends Controller {
public function createHolidays() {
// first create the reference of this controller
$b = new TargetsController();
$mob = 9898989898;
$msg = "i am ready to send a msg";
// parameter will be same
$result = $b->mytesting($msg, $mob);
log::info('my testing function call with return value' . $result);
}
}
// this controller calls it
class TargetsController extends Controller {
public function mytesting($msg, $mob) {
log::info('my testing function call');
log::info('my mob:-' . $mob . 'my msg:-' . $msg);
$a = 10;
return $a;
}
}

Related

Deciding which controller#action to be called based on a given parameters

I have to build an api.
It has one route. The client is sending a POST request with an XML.
Based on that xml, I have to decide witch controller#action to be called.
And I have a lot of controllers.
Unfortunately I can't modify the client side.
Do you have any suggestion how can i do that in a Laravel way?
For example
POST["body"] =
"...
<controller>content</controller>
<action>index</action>
..."
I want to call a ContentController::index()
Thx!
Thx for the reflection stuff. It is a big magic, worth the effort to look into it deeper.
I have no problem to parse the xml. So here is a simplier example
URL: /api/request/content/show
Routes.php
Route::get('api/request/{controller}/{action}', 'ApiController#request');
ApiController.php
class ApiController extends Controller
{
public function request($controller, $action)
{
//some error check
$controller = 'App\Http\Controllers\\' . ucfirst($controller) . 'Controller';
$params = "Put some params here";
$reflectionMethod = new \ReflectionMethod($controller, $action);
$reflectionMethod->invoke(new $controller, $params);
}
}
ContentController.php
class ContentController extends Controller
{
public function show($params)
{
dd($params);
}
}
And it is working!
Thx a lot!
A better option is to use App::call(); invoking controller with ReflectionMethod might not let you use response() inside your new forwarded controller and other laravel goodies.
Here is my try on this: /api/request/content/show
Routes web.php or api.php
use App\Http\Controllers\ApiController;
Route::get('api/request/{controller}/{action}', [ApiController::class, 'request']);
ApiController.php
class ApiController extends Controller
{
public function request($controller, $action)
{
//some error check
return App::call('App\Http\Controllers\\'.ucfirst($controller).'Controller#'.$action);
}
}
ContentController.php
use Illuminate\Http\Request;
class ContentController extends Controller
{
public function show(Request $request)
{
dd($request);
}
}
This will allow you more freedom.

How to call one method from another method from the same controller in Kohana 3

I have two methods and I want in first method to call the other method. They are in the same controller. I tried in this way but I'm getting error:
Call to undefined method Controller_User::getUser()
My controller looks like that:
<?php defined('SYSPATH') or die('No direct script access.');
class Controller_User extends Controller {
public function action_index (){
$id = $this->request->param('id');
$user = self::getUser($id);
}
public function action_getUser ($id){
//some code here
}
}
Both functions are in same class so use $this-> to call other method in same class in your case as kingkero mentioned in comment user $this->action_getUser($id)

Laravel 4: Reference controller object inside filter

I have a controller in Laravel 4, with a custom variable declared within it.
class SampleController extends BaseController{
public $customVariable;
}
Two questions: Is there any way I can call within a route filter:
The controller object where the filter is running at.
The custom variable from that specific controller ($customVariable).
Thanks in advance!
as per this post:
http://forums.laravel.io/viewtopic.php?pid=47380#p47380
You can only pass parameters to filters as strings.
//routes.php
Route::get('/', ['before' => 'auth.level:1', function()
{
return View::make('hello');
}]);
and
//filters.php
Route::filter('auth.level', function($level)
{
//$level is 1
});
In controllers, it would look more like this
public function __construct(){
$this->filter('before', 'someFilter:param1,param2');
}
EDIT:
Should this not suffice to your needs, you can allways define the filter inside the controller's constructor. If you need access to the current controller ($this) and it's custom fields and you have many different classes you want to have that in, you can put the filter in BaseController's constructor and extend it in all classes you need.
class SomeFancyController extends BaseController {
protected $customVariable
/**
* Instantiate a new SomeFancyController instance.
*/
public function __construct()
{
$ctrl = $this;
$this->beforeFilter(function() use ($ctrl)
{
//
// do something with $ctrl
// do something with $ctrl->customVariable;
});
}
}
EDIT 2 :
As per your new question I realised the above example had a small error - as I forgot the closure has local scope. So it's correct now I guess.
If you declare it as static in your controller, you can call it statically from outside the controller
Controller:
class SampleController extends BaseController
{
public static $customVariable = 'test';
}
Outside your controller
echo SampleController::$customVariable
use:
public function __construct()
{
$this->beforeFilter('auth', ['controller' => $this]);
}

Convenient Way to Load Multiple Databases in Code Igniter

I've added the appropriate configuration arrays to database.php and they work, however, I would like an easier way to access the different databases. Right now I have to do something like this in every controller method:
function index(){
$BILLING = $this->load->database('billing', TRUE);
$INVENTORY = $this->load->database('inventory', TRUE);
$data['billing'] = $BILLING->get('stuff');
$data['inventory'] = $INVENTORY->get('stuff');
}
I'd like to be able to put those first two lines in some sort of before filter or pre_controller hook.
You could simply load the database instances globally in your constructor, then they would be available to all controller methods...
example controller
class Example extends CI_Controller {
//declare them globally in your controller
private $billing_db;
private $inventory_db;
function __construct() {
parent::__construct();
//Load them in the constructor
$this->billing_db = $this->load->database('billing', TRUE);
$this->inventory_db = $this->load->database('inventory', TRUE);
}
function index() {
//Then use them in any controller like this
$data['billing'] = $this->inventory_db->get('stuff');
$data['inventory'] = $this->billing_db->get('stuff');
}
}
And if these same databases are used across multiple controllers, you might consider extending the base controller to include these global variables and load them in the constructor of your base controller in MY_Controller.php
example MY_Controller.php
class DB_Controller extends CI_Controller {
//declare them globally in your controller
private $billing_db;
private $inventory_db;
function __construct() {
parent::__construct();
//Load them in the constructor
$this->billing_db = $this->load->database('billing', TRUE);
$this->inventory_db = $this->load->database('inventory', TRUE);
}
}
Then you'd use it like this...
class Example extends DB_Controller {
function __construct() {
parent::__construct();
}
function index() {
//Then use them in any controller like this
$data['billing'] = $this->inventory_db->get('stuff');
$data['inventory'] = $this->billing_db->get('stuff');
}
}

Codeigniter: Set 'global variable'

If I want to set a variable that my whole controller can access, how do I do it?
Right now, in every function I am setting
$id = $this->session->userdata('id');
I'd like to be able to access $id from any function w/o defining it for each controller. :)
If there's a better way, I'm all ears! I'm a noob!
To elaborate on Koo5's response, you'll want to do something like this:
class yourController extends Controller {
// this is a property, accessible from any function in this class
public $id = null;
// this is the constructor (mentioned by Koo5)
function __construct() {
// this is how you reference $id within the class
$this->id = $this->session->userdata('id');
}
function getID() {
// returning the $id property
return $this->id;
}
}
See the manual for more information on PHP properties and constructors. Hope that helps!
If with global you mean the scope of a single controller, the above answers are correct. If you want to access variables from multiple controllers, I recommend defining a BaseController class and then extending your normal controllers to inherit from that BaseController:
class yourController extends BaseController {}
I use this all the time for both global variables and methods.
Define that very line in a constructor only
You can use this method too inside your controller
function __construct() {
// this is how you reference $id within the class
DEFINE("userId",$this->session->userdata('id'));
}
And Call It As :
function getID() {
// returning the $id property
return userId;
}

Resources