Passing arrays in MVC framework - php

Okay so this is a bit complicated but I will try to explain it as simple as possible.
I have a Model class which does all the activity and stores information in arrays.
I have a Controller class which makes a new Model class and calls required action from Model class to perform the activity.
But all that has to happen from a View file. So I submit a form from my View file, refresh the page and upon refresh, my Controller class checks if the form has been submitted or not, if true then it starts creating an object from my Model class.
Now, here's the part I am having problem. I again need to redirect the page within the Controller class, basically what it is doing is upon refresh it is actually calling the action within the Controller class itself according to data being sent by the Model class. e.g
In my Controller class there is a constructor that creates a new Model object calls Model action and has if and else statement to check for the data being sent by Model class.
Now, based on the value it calls/redirects to my two other action in Controller class. But as I redirect using
header("model/controller/");
my arrays are lost and there is no way I can pass my arrays from Controller to the View.
I have tried
header("model/controller/".$array);
and passing it through urls. But I would rather not pass it through urls.
So is it even possible to achieve what I am trying to accomplish?
Also, sorry if this might be a naive question or a very bad programming practice, I'm just learning. Critiques are very much welcome.

What you're asking is How to persist data between two HTTP requests, and the answer is usually to use sessions. It has nothing to do with MVC.

I think the only way to pass it like that is to use
$data = implode('/',$array);
header("model/controller/".$data);
and when receiving them, in your model use this code:
$data = explode('/',fun_get_args());
// OR
$data = explode('/',$requestURL);
// $requestURL to be replaced with a function depending on your MVC
Hope this may help you

Related

Should I do data insert for a model inside the controller or inside the model?

As my question title states I would like to know all the best practices and pros/cons of following the "Laravel way" of inserting the data in the db.
Is it a bad practice using the Model::create([...]) for inserting a new row in the database which is related to that controller's model?
Is creating a separate function inside the model itself a much better practice?
If so, why?
It depends on size of your project you can use your models directly in your controller and use the fluent interface of Eloquent to do your logic.
There is nothing wrong that you call a model in a controller to get data from database.
If there is some complicated query you can create method in your model and than call that method in controller ...
In laravel you can use insert in controller , view(blade) or even in route .
But recommended is on your controller. This help to make your code clean
You can take a look for resource controller. It has already predefined logic like store() method where you can put some Model::create(), as you said.
That's not bad if you also create a method inside model and call it from your controller.
I think, that create() method for straght storing some data from request (from some form on front-end, as an example) is enough. But if you want/need to make more than straight storing model, a separate method inside model might take place. Apart to avoid controller's method overgrowth and keep your code pretty.
The answer really depends on, so maybe you will shed some light on the logic you want to implement.

Calling a Model Function in View?

I have a function called getThumbnail() in model.
How do I call this function in the view file.
Currently what I have to use is:
<?php
$tmp = new Model();
echo $tmp->getThumbnail(1);
?>
Is there any other way to accomplish this, because calling to Model directly from View doesn't look right.
How to do this correctly is quite a broad topic, there's no one correct answer. However, one thing I would definitely point out is that instantiating a model class inside the view is definitely wrong. Instead, you should either:
pass an instance of Model from the controller to the view, or
pass a "dispatcher" object from the controller to the view which allows the view to call any or some model functions indirectly, e.g.:
echo $dispatcher->dispatch('Model', 'getThumbnail', 1);
It makes a lot of sense if the model methods this dispatcher allows are restricted, to enforce decent separation of concerns. For example, the view should never make any calls that modify state in the model, like User::createNewUser or some such. The view should only be allowed to call "passive" model methods to get data.
The main point being here that you want to inject dependencies into the view, instead of hardcoding specific model calls directly. This pretty much goes for any dependency, not just view-model relations.
It's not a good idea to call to Model from the View.
Views are the minions of the controller. Model should be communicated only from the controller.

Firing Events in MVC (specifically in PHP, if it's needed)

I have searched on SO about this question, but I basically haven't found one concerning this particular scenario; hence, my reason for asking.
I have a basic, abstract understanding of the MVC pattern: Controller calls the right Model based on the action needed; the Model contains the actual business/data logic, and the View displays the result. What I am having trouble understanding is the actual implementation.
Originally, my assumption was this: Controller calls Model; Model processes information, and returns the data back to Controller; Controller call the View, passing this
data to the View, which simply displays it. After reading more articles on MVC, I discovered that the Model doesn't really pass the data back to the Controller; rather, it fires an event, which allows the Controller to call the proper View.
My question centers on this event firing part:
Q.1: Must an event really be fired? Once the Model completes its processing, and returns control to the Controller, can't the Controller simply call the View?
Q.2: In an actual implementation, a Model object is injected into a Controller class. So, Model object basically has no idea what Controller called it. How does it know what Controller to fire an event to? And how do we know what Controller is expecting that notification?
Q.3: The Controller calls the View, injecting it with the current Model object, so the View can use it to obtain the needed data. Is this correct or wrong? If wrong, why is it wrong, and what is the proper way to do it?
I have read my questions on MVC on here and other sites, viewed MVC diagrams, but I haven't been able to really connect the dots the way it's supposed to be connected.
Thanks.
There are many way's on how the different components on MVC are linked together. I think there is no 'Golden Rule'.
I use it the way shown in this picture:
The creation of objects is then like this:
the app object creates a controller, depending on the route. The router is injected into the controller.
The controller creates a model, depending on the route. The model is created by a IoC container.
The controller creates a view, and injects the model into the view.
In my situation I can answer your questions like this:
Q1: No, I do not use events. There is no need. The controller calls the model, and when done the model has state, and can be used by the view.
Q2: I do it just the other way, the controller creates the model. The model has no knowledge about the controller, or view.
Q3: this is the way I implement it.

How to access a controller from a model using CodeIgntier?

I want to access a controller, which is located in application/controller/example.php, from a model - located in application/model/users.php
class Users extends CI_Model {
//access the example.php controller
}
Who could i accomplish this ?
You don't want to ever do that, hence why CodeIgniter cannot do it. You should be accessing everything else from your Controller, not the other way around.
A good old resource from CodeIgniter :)
http://codeigniter.com/user_guide/overview/mvc.html
You dont have to access an controller from a model. Models (Views, helpers, libraries ect) should all be accessed from controllers. ( Model are used from manipulating data ( usually in database ) )
The idea behind the MVC is to have a Model, Viewer and Controller.
In other words the Controller handles the request, the Model gets the data and the Viewer displays something to the user.
The Model is used ONLY to manipulate the data - doesn't matter if it's a database connection or other data resource.
Model is where you store your bussines logic. Controller is where you call things and operate with data. Views are for creating output.
Bassically you can do everything from withing controller, but that is wrong, since it does not gain you any clarity. Try to offload as much as possible to models and views and keep controllers small and readable, well commented.

about MVC application

I have seen all types of tutorials:
View running controller, controller passing model to the view, controller setting setter of view.
An example: MVC for a reading of a news.
The controller loads the Model. If the result of the model is 'false' I can call another method from another model containing different block.
The View class must be relevant to, View_found View_not_found?
if (model-> news === true) {
$ comment = model-> comment ()
}
Would this code snippet be the responsibility of the controller or is it a rule that such logic should belong to business model?
in my experience, i tend to program the model and view as "blind". the model and view only receives parameters needed and then spits out what is needed. they should do minimal to no logic at all.
for the model it performs minor checks, like parameter type and validity and returns either a result or false. the controller does not know how the data is stored, where, why etc.
for the view, it should receive a string preferably through only one entry point, a function which will do the escape and echo. other than that, the controller should never echo to a page.
everything else is for the controller to digest like validation, calling what's needed, determine what is what. the controller sees everything:
//get from model, pass parameter - that's it
if (model-> news ('all')) {
//manipulate data for result
//get appropriate view
view->parse(html); //pass html to view, that's it
} else {
//manipulate data for no result
//get appropriate view
view->parse(html); //pass html to view, that's it
}
If you want to find model News comment, you need to create Comment model and get it from your dataProvider and render to view.
Here is a part of controller action code :-). All logic must be in controller. Views is only render content parts.
UPDATED I recommend using here dataProvider. Model method (getter) can return DP object for model.
It depends which framework you're using.
Like said Rasmus Lerdorf
MVC is the current buzz in web application architectures. It comes from4event-driven desktop application design and doesn't fit into web application5design very well. But luckily nobody really knows what MVC means, so we can6call our presentation layer separation mechanism MVC and move on.
As a matter of fact, in web application, it is common to use "action oriented MVC" instead of "event MVC".
You've got a controller that knows his model, and the view to apply.
To display news, You must have a News class which is your model, a NewsProvider which deals with your database.
Your controller compute the datas given by the database and the user and call the proper view.
The best practice is to keep business logic in Models
see below links for reference
http://www.yiiframework.com/doc/guide/1.1/en/basics.best-practices
ASP.NET MVC - Should business logic exist in controllers?
http://blogs.msdn.com/b/aspnetue/archive/2010/09/17/second_2d00_post.aspx

Categories