Coding standards - Controller vs view - php

I am writing this web project in which one of the views will be having two types of boxes. There is an array and based on type of the values of each item in the array i have to display one or the other box.
Qn is: Should i write the html code for boxes in the controller as two methods or should i write it as two functions and call on it from inside the view itself? Both methods sounds not so good. Your thoughts,suggestions or any ideas for a method outside of two i mentioned above?
Here is a link i saw which closely resembles my thought on writing html code in controller. PHP coding standards

MVC is a guideline. It's there to help you, if it's hindering you getting the job done then something is wrong.
I'm not sure I understand your question properly, but if you mean that you have to display different HTML depending on the data passed to you during run time, then I'd suggest you package that code in a helper function and call it from your view.
On the other hand, if you mean that you're views are well defined and unchanging, I'd just do the checking in the controller and display the appropriate view.

You should follow the common way of dealing with view using MVC guidelines, meaning you should populate a variable with your two functions inside the controller with the values - then inside your view, you should fetch the raw data and display it as you choose.

I'm not sure I understood you completely, but :
No HTML code in your controller.
If you have 2 different HTML code,
and one controller action, then you
need 2 views. In your controller, you
can then choose which view to use.

Related

How to integrate menu/footer/menu in PHP MVC

i know that this question already has been asked. But i still dont understand it.
Right now im trying to understand how to make use of the MVC Modell.
But i dont get how to integrate everything and right now I am hesitating to use a framework before i really get it.
What I try to achieve:
I want to have a header, a footer and a menu which remain the same all the time.
Like this:
HEADER
MENU
{CONTENT}
FOOTER
So my thinking is:
My Controller gets some Information, lets say its a User-ID.
Controller calls a method from the Model:
Get all DATA from USER with ID: 1
Then the controller passes the DATA into a view, lets say a list.
So where to go from here?
Should the controller pass this view into another view?
Like:
$site = new View(); <br>
$site->wholeSite($content);
and then site is something like:
HEADER
MENU
{$content}
FOOTER
Please excuse my simple approach, im just trying to get the basic idea behind it and i already read the first 20 pages of googling it.
Just cant get my head around it.....
It would be really nice if you would explain it for an Beginner :)
Thanks in advance!
you can call multiple views from the control like:
$this->load->view('header',$data);
$this->load->view('menu',$data);
$this->load->view('content',$data);
$this->load->view('footer',$data);
If you have a nested div then you can use regular include function like from a particular view file.
include('footer.php');
According to the path of the view file. The data also gets transferred from parent view to the included file.
Generally MVC apps have a universal layout view which contains the header, footer and menus. Sometimes data required for that is handled outside the controller, in say your init script or bootstrap.
An MVC purist might pass all data the layout requires from the controller, but that can be repetitive, although setting the data in an abstract controller construct might alleviate that.
On the question of views and sub-views there are generally two solutions:
A.) You have one principle view which all required data is passed to. In that view sub-views (partials) are called, and data is passed down into them.
B.) You instantiate all your views in the controller, passing all the data they need directly into the view, you would then pass views as parameters into other views.
Both methods have their pros and cons. I find the first option leads to less Fat Controllers, so I usually go with that.
I'd recommend you learn an existing MVC framework ( CodeIgniter, now defunct is basic enough to make it a good entry point), as that will show you how things are done.

Creating a subview in PHP MVC

I recently went through some tutorials on how to program your own PHP MVC framework. To avoid some questions and comments: I don't want to use it in a productive environment, I just like to fiddle and get the idea of whats going on in MVC.
So far I am able to have single pages eg. http://domain/news/show/3 shows me the news-record from the database with id 3 and http://domain/news/all lists them all on one page.
Now I have multiple entities and thus multiple lists and want them all to appear on one page. Preferably the page you see when you open http://domain/
Do I have to write a new model and controller that makes calls to the other models? I'm kinda unsure how to achieve this.
There is no strict definition or convention on this that I'm aware of.
What I would do is this:
Class Overview
Controller_Homepage
Controller_News
Model_NewsArticle
Behavior
Controller_Homepage
Action_Index fetches multiple Model_NewsArticle entities, has them rendered, and passes the output to view. Also fetches any other entities you may need and gives their rendered output to view.
Controller_News
Action_List fetches multiple Model_NewsArticle entities, has them rendered, and passes the output to view.
Action_View calls Model_NewsArticle::factory($id), has it rendered, and passes the output to view.
Model_NewsArticle
Contains a static factory method that accepts an $id. Returns an instance of Model_NewsArticle.
Contains methods used to find multiple articles. A query builder would be nice here.
That's by no means comprehensive and I've left out lots of little details, but it's fairly simple and is pretty dry.
This is a matter of preference really. Having another controller and model makes code separation easier in larger projects. Personally, I would only make a new controller since it is a different page with potentially different actions, and I would use the existing models to get the data to keep your code DRY (Don't Repeat Yourself).

Beginner CodeIgniter concepts - Reusable view code, where to go? (Helper?)

I am a beginner with CodeIgniter still struggling to get a complete grasp on how to use the MVC ideology most cleanly.
I am writing a basic CMS system with the ability to vote on entries and follow people etc, consequently, I have found myself using the same or similar pieces of code across multiple views here and there consisting of various pieces of html and logic such as:
Voting panel
Follow/Unfollow panel
Login/Logout panel
Code to check if a user is logged in etc...
I am wondering where to put this code so it can be unified? I am thinking a helper is the way to go? If I declare the helper in the controller, it can be called from the corresponding view right?
Some of the elements are dynamic - such as a follow/unfollow button - It would need to check if you are already following the user or not and display the appropriate button, which would require a model to check. What I have now is that all the logic is in the controller and it returns an appropriate button, but it seems weird to be returning formed html code in a controller return as well. Should it be more like:
controller checks if you are following someone
the controller passes a boolean to the view
the view calls the helper with this value to draw the appropriate button
Also, as a secondary question, I have been doing a fair bit of looping through mysql arrays in foreach loops to process mysql results returned from the view. It seems like my views are getting somewhat complicated, but I can't think of another way to do it, although perhaps this should be done in another helper as well?
Apologies if this is a naive or repetitive question, there is indeed a lot of discussion surrounding this subject but it is not always easily relatable to another project.
Helpers are certainly one way to modularize anything that isn't DRY. Another is to use Partial Views. CodeIgniter looks like it supports partial views. Here's a good breakdown - not PHP specific but the discussion should be agnostic.
As far as handling user logins is concerned, you will probably want to use a static class and the singleton design pattern, which will allow you to check to see if a particular user is logged in or not anywhere in your application. There is a good tutorial here
http://www.phpandstuff.com/articles/codeigniter-doctrine-scratch-day-4-user-login
Loading the helper, I don't believe loading it in your controller will automatically load it in your view. I think you have to re load the helper in your view file, or you have to autoload the helper. (cant remember off top of head but Im pretty sure).
Regarding looping through the mysql results, you should be using a model for this, always. Any functions which are grabbing or sorting information from your applicaiton, should be done within the model. Then, in your view file you loop through the results and format the data how you choose to.
When developing http://newspapair.com which has the vote functionality you mentioned I used helpers and custom classes to spread the functionality across multiple views.
Helper - has functions without a class. So a standalone function or group of functions can be placed in a file and saved as a helper.
For instance I used a helper with generic form processing functions for NewsPapair, instead of a static class. But this is not the "best practices" thing to do. I did it this way because I already had the functions from a previous project.
As far a looping through MySQL results, try to write a query that allows the DB Server to do the heavy lifting. This will make your code more efficient. Perhaps ask a question about a specific query with example code. Plus do all of the data gathering in your Model.

When to use model or helper

I am playing around Codeignter and was curious about the structure of the application:
I am not sure when to use the model ( apparently it isnt a hard requirement)
I have a part of the header that is dynamic, so I run conditional statements ( if () {..} else {..} ) for the sake of code cleanness and clarity. Should I turn that part into a helper and refer to it instead? Or does that sound like too much of a stretch?
The models are best used for data gathering and formatting methods. Such as polling the database for blog posts and then creating post objects of them and returning them.
Then the controller uses them to fill views with the data desired, such as a title, a date, an author, and a shortened body summary.
As far as the header part, consider creating smaller views to encapsulate complex code, like a menu highlighter switch or ifs, away from more clear-cut code. Consider over-building those views. Nothing wrong with creating a view just for one tab on a menu, then calling it 10 times with different data for each of the menu items in another view.
While it seems silly for a menu, it becomes indispensable for uses like boxes to wrap widgets in, or built-in validation on a textarea view.
I am not sure when to use the model ( apparently it isnt a hard requirement)
Models are part of the MVC structure. I'd recommend you to read about it.
I have part of the header that are dynamic, I run conditional statements ( if () {..} else {..} ) for the sake of code cleanness and clarity should I turn that part into a helper? and refer to it instead? Or does that sound like too much of a stretch?
This article explains you how to use: Helpers in CodeIgniter.
You should use a model if you're reading/writing data to a database (or another data source).
You should use a helper to help you with reusable tasks. For example, you may have an authentication helper, or a form helper, etc.
I would have thought you'd be able to extend a helper to return a random header image URL you can use in an img tag, although it's been a while since I've working with CodeIgniter.

Where to put certain logic in CakePHP

I've recently started to rewrite a project I did a few years ago using CakePHP. I'm trying to do everything 'right' this time, so maybe someone get give me a a pointer on doing to the following:
I'm showing a simple table from a table using Model->find('all') in the View. There are two boolean fields in this table, that together make up something I need to show to a user. So: 0x0 = 'A', 1x0 = 'B', 0x1 = 'C', 1x1 = 'D'. Where should I put this logic? I've been thinking about the following methods:
The view
A View helper
The controller
Something in the Model so that Model->find('all') outputs this value (is that even possible?)
This task might seem trivial, but I think it might learn me getting this project organized and maintainable from the start.
Thanks!
Well, it depends on the type of logic for making up final table (is it presentation or business?).
Imagine you add new type of UI, for example command line interface. How would you show your table there? The data passed to View has to be same for both HTML and console presentations. So the logic which is responsible for preparing that data - is business logic and it should be placed in Model. The logic responsible for displaying the data should be placed in View (maybe in view helper if it's used more than once).
And never place this kind of logic in Controller.
If it's something you're going to use all over the place I would put it in the model. You can either put a method on the model that gives that value back or loop over all the rows you've retrieved in an afterFind callback and set it as a proper field.
I put this kind of logic in the view if it is something that is going to determine rendering style. In that way, the designer has maximum access and can style accordingly.
On the other hand, if the two columns only exist for convenience in datamodelling, put it in the model. The designer shouldn't even be aware of other possibilities!
In the controller! The methods from the model comes in the controller. The view is just for output( like HTML UI programming.)

Categories