I am building an application in Laravel. I need to pass some data between two methods in two different controllers. Let me explain You,
I have a controller sellerRegisterController which has a method verifySeller,
class sellerRegisterController extends Controller
{
public function verifySeller()
{
//some logic here
}
}
The above veirfySeller method works on some logic and create a varible ID, I want to pass that varible ID data to another method (submitSellerDetails) in different controller (sellerDetailsController).
class sellerDetailsContorller extends Controller
{
public function submitSellerDetails()
{
//some logic here
}
}
In a nutshell I want to know how can I pass data/variable from one method to another in different controllers? Thanks
If I were you, I would define both methods verifySeller() and submitSellerDetails() in the same controller.
Your controller will look like this:
class sellerRegisterController extends Controller
{
public function verifySeller( Request $request )
{
//some logic here
// passing data to another method in the same controller
$this->submitSellerDetails( $request );
}
public function submitSellerDetails( Request $request )
{
//some logic here
}
}
If you don't want to pass $request variable but some other variable instead, you can do something like this:
class sellerRegisterController extends Controller
{
public function verifySeller( Request $request )
{
//some logic here
// passing data to another method in the same controller
$this->submitSellerDetails( $variableContainingYourData );
}
public function submitSellerDetails( $someArgument )
{
//some logic here
}
}
There's another way to handle it. You can define a variable in the in your controller, assign it whatever data you want inside verifySeller() method and then call submitSellerDetails() method and use that variable inside it.
Update:
class sellerRegisterController extends Controller
{
private $someVariable;
public function verifySeller( Request $request )
{
//some logic here
// assign data which you want to access inside submitSellerDetails()
$this->someVariable = 'some data';
// calling submitSellerDetails() method
$this->submitSellerDetails();
}
public function submitSellerDetails()
{
//some logic here
//do whatever you want with $this->someVariable;
}
}
Hope it helps.
Related
Simple example
I would like to know if there is any possible way that $data could already exist without being set in that method, and if so how to set it.
public function index(){
if(isset($data)){
//how is this possible?
} else if(isset($this->data){
// set in parent::__construct
// ok i'm going to have to set $data in every method in every controller
$data = $this->data;
}
}
additional info
This is my specific problem,
I am using a framework with a controller class which is extended for every controller.
class ControllerBlog extends Controller {}
Every method in every controller perform a few almost identical tasks. Some of these tasks return data within the scope of the method called.
//e.g
public function index(){
$this->loadthis('blog');
$this->loadthat('blog');
$data = $this->get_this('blog');
...
...
$data['title'] = 'blog title';
use_data($data);
}
I would like to move these tasks to Controller class function __construct to limit the amount of code repeated.
<?php
class Controller {
public function __construct() {
//load this and that and return data;
$data = $this->load_and_return_all(get_class($this));
//class level
$this->data = $data;
}
}
is there a way to get the $data variable for use within the scope of the method without the need of adding any additional code to every method of every controller?
class ControllerBlog extends Controller {
public function index(){
//adding this to every method seems silly
$data = $this->data;
// i would like $data to be set in the construct;
}
}
this supposed to be an MVC framework
(i am learning by doing)
class load{
public function model(){
// some code...
[...] = model[$modelName] = new $modelName();
}
}
this class handles all load option in to the controller..
class _framework{
public $load; // object
public $model; // array
function __construct(){
//some code...
$this->load = new load();
}
}
this is the framework of the controllers
the controller extends this class.
edit:
it should use like this:
class newController extends _framework{
public function index(){
$this->load->model('modelName'); // for loading the model.
$this->model['modelName']->modelMethod(); // for use the model method.
}
}
my problem is where the [...].
how can I get the new model to the array in the framework class??
If you want to get an array out of your model object,
you can define its public method toArray:
class modelName {
public function toArray () {
$array = ...; // get your array here
return $array;
}
}
Then you can call it from outside and get your array:
$myArray = $myModel->toArray();
Your model should encapsulate its data and make them accessible via API like that.
I would not call an array a model though. A model is a layer with many classes serving the purpose of the model - storing your data, peforming their validation, whatever other data-related business logic and providing API to access the data.
Also it is common to capitalize your classes.
class LessonController extends \BaseController {
protected $lesson;
public function __construct(\Lesson $lesson)
{
}
public function edit($lesson)
{
var_dump($this->lesson);
}
}
Here how can I var_dump the selected model based on the user going to a route like domain.com/lesson/edit/{id}?
What you're injecting isn't an instance of the model, but rather the class that provides access to instances. Your calls will look like un-injected calls but with $this->lesson replacing Lesson::.
To find a particular instance, then, you'll call
$lessonInstance = $this->lesson->find($id); // if not injected, would be Lesson::find($id)
var_dump($lessonInstance);
I want to make some action (php script) before all actions in my frontend app and then pass a result from that script to actions in variable - so I can get variable value from all actions. Where should I declare sth like this?
If the filter solution dont feet your needs, you can also create a base action class with a preExecute function:
// app/frontend/lib/baseActions.class.php
class baseActions extends sfActions
{
public function preExecute()
{
$this->myVar = .... // define your vars...
}
}
Then your module actions class extends your baseActions class:
// app/frontend/modules/myModule/actions/actions.class.php
class myModuleActions extends baseActions
{
public function executeIndex(sfWebRequest $request)
{
// var $this->myVar is available in any action and in your template
...
}
}
if you have to use the preExecute function in your module class action, remember to call parent::preExecute() in it.
What kind of information ?
I would recommend you to use filters.
In your apps/frontend/config/filters.yml:
rendering: ~
myfilter:
class: myCustomFilter
Create the file lib/filter/myCustomFilter.php:
<?php
class myCustomFilter extends sfFilter
{
public function execute ($filterChain)
{
if ($this->isFirstCall())
{
// do what ever you want here.
$config = Doctrine_Core::getTable('Config')->findAll();
sfConfig::set('my_config', $config);
}
$filterChain->execute();
}
}
And then, every where, you can retrieve your data:
sfConfig::get('my_config');
I'm only interested in handling GET or POST requests, so I designed this abstract class to determine which request has been made and to subsequently call the appropriate function. I would really appreciate feedback on this. Thanks!
PS I think this should be a community wiki, but I'm not sure how to set it as that.
abstract class AHttpRequestHandler
{
public function handleRequest()
{
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$this->handlePostRequest();
} else if($_SERVER['REQUEST_METHOD'] == 'GET') {
$this->handleGetRequest();
} else {
$this->handleIllegalRequest();
}
}
abstract protected function handleGetRequest();
abstract protected function handlePostRequest();
protected function handleIllegalRequest()
{
throw new Exception('Illegal request detected in HttpRequestHandler::handleIllegalRequest().');
}
}
In response to comments:
I will only be handling one or the other (GET or POST), never both at the same time.
Either an HTML form will be submitted via POST, or a redirect will be made with a query string, which will be a GET request. I am not familiar with how a mixed request could be made (both GET and POST), but since this is a personal project I have control over whether it happens or not.
I use the AHttpRequestHandler class (above) by implementing the handleGetRequest() and handlePostRequest() methods in a sub-class, which is and abstract controller, AController. Then, for each page of my CMS, I create a sub-class of AController, such as ImageUpload or ImageDetailsEditor. I can provide more details if it will help.
Here are the AController, Controller, and View classes:
AController
abstract class AController extends AHttpRequestHandler
{
protected $view;
public function __construct()
{
$this->handleRequest();
}
protected function handleGetRequest()
{
throw new Exception('handleGetRequest not yet implemented.');
}
protected function handlePostRequest()
{
throw new Exception('handlePostRequest not yet implemented.');
}
abstract protected function initView();
}
Controller
class Controller extends AController
{
protected $content;
public function __construct()
{
$this->view = new View();
parent::__construct();
}
protected function handleGetRequest()
{
$this->content = 'GET Request';
$this->initView();
}
protected function handlePostRequest()
{
$this->content = 'POST Request';
$this->initView();
}
protected function initView()
{
$this->view->content = $this->content;
$this->view->display();
}
}
View
//An over-simplified view for example use only
class View
{
public $content;
public function display()
{
echo "<p>$this->content</p>";
}
}
The actual use:
require_once 'Controller.php';
$controller = new Controller();
First of all you can make a GET request and a POST request in the same time. Think of a form that you post but the url has some variables in the query ( get ).
1.I don't understand the need for such a class but the first thing you could do is make two separate classes for post and get that extend the AHttpRequestHandler class. That way you only need an abstract function handleRequest that you will implement in the child classes.
2.You should apply "Intention Revealing Names". Your class should be RequestHandler and your methods should not contain Request in them. You know that from the class name.
3.Think about this: you might need to handle the post request in one controller. So you will have to add the second abstract method each time just to respect the abstract class.
4.You should not make circular calls between classes ( The Hollywood principle ). handleRequest is called from the child class, and then the parent calls handleGetRequest or handlePostRequest from the child.
Like I said, you are the developer, you know each controller what will use:POST or GET ( what about COOKIEs? ), so you can handle them at controller level without the need to extra classes just for the sake of it.
see ref
see ref
see ref
see ref
And the Controller should receive a request (command), not extend the request to keep things apart. Have no catch phrase for that, perhaps seperation of concerns. That's an extension to 1. above but only if you really need a request object.
Having an abstract class for requests is a good idea and it is there in all frameworks. But I dont think its good to extend this class by all controllers. A better solution will be to separate this to two, an abstract request class and base controller class. In request class you can have methods to identify whether it is a get request or post request, like
class Request{
public function isPost() {
return ($_SERVER['REQUEST_METHOD'] == 'POST');
}
public function isGet() {
return ($_SERVER['REQUEST_METHOD'] == 'GET');
}
}
Also we will have a base controller class with at least the following options
class Controller
{
public $request;
public function __construct() {
$this->setRequest(new Request());
}
public function setRequest(Request $request) {
$this->request = $request;
}
}
All our client controllers will extend the base controller as usual. The advantage of this method is client controllers will have the freedom to determine the request type. if they want to make use of GET and POST request at a time, that also will be possible. The above given is of course an incomplete one. You need to add more methods to the base classes or not is your choice.