im developing a web application, using multiple pages, each with their own controller.
The problem now is that there are some variables in a controller, created for one page, that are required for an other page ( with a different controller).
Therefor i need to load one controller into the other one.
I did this by adding
App::import('Controller', 'sections');
$sections= new sectionsController;
$sections->constructClasses();
to the controller, but this doens't seem to work..
Maybe u guys have some ideas?
Thnx in advance!
I think there're some misunderstandings in your mind about MVC architectural pattern.If you need some bullet for your gun,just get the bullet itself,and it's not neccessary to get another gun with it.So I hope you understand loading controller is really a bad idea.
Also if you want some variables accessable by all controllers,as Gaurav Sharma
mentioned ,you can use Configure::write() to store data in the application’s configuration app/config/core.php.e.g
Configure::write('somekey',$someval);
Then you can get $someval by Configure::read('somekey') in any controller.
You can use any one of the methods below to access a variable anywhere in the cakePHP application.
1.) use the configuration class OR
2.) use session for those variables
I've been working on this this morning. I actually get the controller name from a database, but I've changed it to use variables instead.
$controller_name = "Posts"; // the name of the controller.
$action = "index"; // The action we want to call.
App::import('Controller', $controller_name);
// Now we need the actual class name of the controller.
$controller_classname = $controller_name . 'Controller';
$Controller = new $controller_name;
$Controller->variable_name = "something"; // we can set class variables here too.
// Now invoke the dispatcher so that it will load and initialize everything (like components)
$d = new Dispatcher();
$d->_invoke($Controller, array('pass'=> '', 'action' => $action));
// And exit so it doesn't keep going.
exit(0);
I honestly didn't bother figuring out what 'pass' is for (I assume variables), but it throws a warning without it.
You will also need to explicitly call $this->render in your $action.
Related
I need to call in checkout/confirm.tpl file a custom function that i've made in controller/product.php
what's the best way to make this?
i've tried this, but doesn't work:
$productController = $this->load->model('product/product');
$productController->customFunction();
yes i find the right answer finally!!! sorry for last bad answer
class ControllerCommonHome extends Controller {
public function index() {
return $this->load->controller('product/ready');
}
}
MVC
in an MVC architecture, a template serves solely for rendering/displaying data; it shouldn't (*) call controller/model functions nor it shouldn't execute SQL queries as I have seen in many third-party modules (and even in answers here at SO).
$productController = $this->load->model('product/product');
nifty eye has to discover that you are trying to load a model into a variable named by controller and you are also trying to use it in such way. Well, for your purpose there would have to be a method controller() in class Loader - which is not (luckily)
How it should be done?
sure there is a way how to access or call controller functions from within templates. In MVC a callable function that is invoked by routing is called action. Using this sentence I can now say that you can invoke an action (controller function) by accessing certain URL.
So let's say your controller is CatalogProductController and the method you want to invoke is custom() - in this case accessing this URL
http://yourstore.com/index.php?route=catalog/product/custom
you will make sure that the custom() method of CatalogProductController is invoked/accessed.
You can access such URL in many ways - as a cURL request, as a link's href or via AJAX request, to name some. In a PHP scope even file_get_contents() or similar approach will work.
(*) By shouldn't I mean that it is (unfortunately) possible in OpenCart but such abuse is against MVC architecture.
$this->load->controller('sale/box',$yourData);
To call ShipmentDate() function of box Controller
$this->load->controller('sale/box/ShipmentDate',$yourData);
May be something like this could help you (or anyone who's interested)
// Load seo pro
require_once(DIR_CATALOG."/controller/common/seo_pro.php"); // load file
$seoPro = new ControllerCommonSeoPro($this->registry); // pass registry to constructor
$url = HTTP_CATALOG . $seoPro->rewrite(
$this->url('information/information&information_id=' . $result['information_id'])
);
return $this->load->controller('error/not_found');
in laravel its so simple just write Controller::call('ApplesController#getSomething');
but there i cant made better than this
$config = new Config();
// Response
$response = new Response();
$response->addHeader('Content-Type: text/html; charset=utf-8');
$response->setCompression($config->get('config_compression'));
$this->registry->set('response', $response);
$action = new Action('product/ready');
$controller = new Front($this->registry);
$controller->addPreAction(new Action('common/maintenance'));
$controller->addPreAction(new Action('common/seo_url'));
$controller->dispatch($action, new Action('error/not_found'));
$response->output();
in this case its well call product/ready
I am interested in having data that can be access through all my views and controllers, but I would like this data to be cleared when the browser is closed or on a logout action.
The reason for this is because I want my views to work only if a variable is set.
eg:
public function adminAction(){
if ($rol_type=='admin'){
$this->renderScript('index/admin.phtml');
}
else{
$this->renderScript('index/adminLogin.phtml');
}
}
I would like also that the admin.phtml view can't be accesed without the variable being set to admin, so that no one can just change the URL and acces admin panel.
I've been reading the zend framework's 2 documentation about session but there is a lot of stuff inside the session module, so I don't know what to use, or where to look for.
I also would be very grateful if you could tell me what is the best way to achive my goal (cause I'm not sure if this is the best way to do what I want to do).
You can use :
use Zend\Session\Container;
In Controller:
$user_session = new Container('mySession');
$user_session->key = "Your Value";
This key can be passed to your view or other models and controllers.
For retrieving we have to do like:
$user_session = new Container('mySession');
$keyValue = $user_session->key; //here you will get the value stored above
Hope that helps
Thanks
I'm new in cakephp and I'm just wondering, how to test models and controllers without using views?
I have to simulate saving data using models and controllers without using froms from views. I was thinking about to make an array with the needed values, but maybe there is a better way to do that?
you can mock your model functions using code like:
$model = $this->getMockForModel('MyModel', array('save'));
$model->expects($this->once())
->method('save')
->will($this->returnValue(true));
You can output variables at any time from controllers (or models) without getting to the views. Yes, it's not how you should do things with an MVC framework, but for testing, it's pretty easy to whack this below your database call in the model/controller:
<? echo '<pre>'; print_r($my_array); exit; ?>
The other thing you can do is at the top of your action function in the controller put:
$this->layout = '';
$this->render(false);
... which will bypass the layout and skip the view rendering, so you can output whatever you like within that function without using the view.
At the beginning of your action, you may use:
$this->autoRender = false;
This will allow you to access your action directly by going to it's path (e.g. CONTROLLER/ACTION). Before passing your data array to save() or saveAll(), I recommend double-checking it with Debugger::dump(), and follow that with die(). This will make the array containing the save data print on your screen so you can verify it looks proper and follows Cake's conventions. The die() will prevent it from actually saving the data.
If everything looks correct, remove the dump() and die() and test it out again.
The first response, from Ayo Akinyemi, should also work well if you are Unit Testing your application.
I have just started learning Code Igniter .
I want to know how can I pass a variable from one controller(first_cont.php) to other controller (second_cont.php) ?
Any help would be appreciated .
Thanks in Advance :)
It will depend on the circumstances. If you want to retain the data for some time, then session data would be the way to go. However, if you only need to use it once, flash data might be more appropriate.
First step would be to initialise the session library:
$this->load->library('session');
Then store the information in flash data:
$this->session->set_flashdata('item', $myVar);
Finally, in the second controller, fetch the data:
$myVar = $this->session->flashdata('item');
Obviously this would mean you'd have to either initialise the session library again from the second controller, or create your own base controller that loads the session library and have both of your controllers inherit from that one.
I think in codeigniter you can't pass variable, between two different controller. One obvious mechanism is to use session data.
Ok, here is something about MVC most will readily quote:
A Controller is for taking input, a model is for your logic, and, a view is for displaying.
Now, strictly speaking you shouldn't want to send data from a controller to another. I can't think of any cases where that is required.
But, if it is absolutely needed, then you could simply use redirect to just redirect to the other controller.
Something like:
// some first_cont.php code here
redirect('/second_cont/valuereciever/value1')
// some second_cont.php code here
public function valureciever($value){
echo $value; // will output value1
}
In Codeigniter there are many way to pass the value from one controller to other.
You can use codeigniter Session to pass the data from one controller to another controller.
For that you have to first include the library for session
$this->load->library('session');
Then You can set the flash data value using variable name.
// Set flash data
$this->session->set_flashdata('variable_name', 'Value');
Them you can get the value where you want by using the codeigniter session flashdata
// Get flash data
$this->session->flashdata('variable_name');
Second Option codeigniter allow you to redirect the url from controll with controller name, method name and value and then you can get the value in another controller.
// Passing the value
redirect('/another_controller_name/method_name/variable');
Then you can get the value in another controller
public function method_name($variable)
{
echo $variable;
}
That all....
If you are using session in the first controller then dont unset that session in first controller, instead store the value which you want in the other controller like,
$sess_array = array('value_name1' => 'value1', 'value_name2' => 'value2');
$this->session->set_userdata('session_name', $sess_array);
then reload this session in the other controller as
$session_data= $this->session->userdata('session_name');
$any_var_name = $session_data['value1'];
$any_var_name = $session_data['value2'];
this is how you can pass values from one controller to another....
Stick to sessions where you can. But there's an alternative (for Codeigniter3) that I do not highly recommend. You can also pass the data through the url. You use the url helper and the url segment method in the receiving controller.
sending controller method
redirect("controller2/method/datastring", 'refresh');
receiving controller method
$this->load->helper('url');
$data = $this->uri->segment(3);
This should work for the default url structure. For a url: website.com/controller/method/data
To get controller $this->uri->segment(1)
To get method $this->uri->segment(2)
The limitation of this technique is you can only send strings that are allowed in the url so you cannot use special characters (eg. %#$)
Using PHP, If I have a model (a class) where I various queries, whatever I need, and in my controller, I use myModel = new CustomerModel(); and later in the controller, say I call myMyodel in the controller (I know looks like codeigniter but I am not using a framework) to:
$data['query'] = myModel.OrderByLastName();
how do I pass that $data['query'] to a view, a separate .php page?
I don't wan to echo anything from my controller.
Also, was hoping this design, the way I explained it makes sense. Or am I wasting time with the model class?
Typically, you'd instantiate a view object:
$view = new View();
Pass it the info it needs():
$view->set($name1, $value1);
$view->set($name2, $value2);
...
Then invoke the view's renderer:
$view->render();
The way Django works is the controller basically renders a template using a templating system. It passes the data in Contexts, like this:
data['query'] = myModel.OrderByLastName();
context = {'data': data['query']}
page = loader.get_template('folder/template.phtml')
return render_to_page(page, context)
roughly.
Obviously, you're writing your own system so you've got some room on exactly how you implement it. I don't know if that's exactly what you want, but it might give you a workable idea.