When to use model or helper - php

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.

Related

How should I divide my code using CodeIgniter?

I have searched the web and found only styling code posts. I want to write site using Code Igniter and I wonder how should I maintain my code.
For example:
Should I use one class for static pages and methods for each page or separate file for every static page. Should I use the same file to load dynamic pages or different one?
Can I use some common code and include it automatically to every class?
How can I have lets say header_view footer_view etc and then just load->view('whatever') and footer, header and other files would load automatically. Maybe there is better way to do that?
In generall what are the best practices when coding using CodeIgniter.
You can use one single class for static pages (and use one method for each page).
You can use the same one to load dynamic pages, but it is better IMO to load them with a separate class. It will be easier to maintain later.
Using common code: You can always override the CI_Controller with your own, and instantiating controllers from yours. Here is an example about how to do it.
You can load multiple views in a single controller function. A view doesn't have to be a full html document. You can also load the same view multiple times (for example in a loop).
Best practices: CodeIgniter is an MVC framework. IMO, MVC is a best practice. Always use the framework's documented features if they are suitable for what you want to achieve (CodeIgniter's documentation is very good. That link is momentarily offline, so please try this one).
Codeigniter is a MVC based framework, MVC is basically used for organizing your code, so at last its up to you how you are going to use it so ease you on the long term.
Basically when I design large projects in codeigniter I tried to to make unit of functionality at one place lets take example of any simple users, messages based project.
I tried to make functionality by grouping main topics, in this example user will be a controller, in that controller there will be methods like login, register, edit, listing, forgot_password now I'll create single model with all the methods which will give data for these above methods. by using this methods our urls will be also meaningfull like /user/login, /user/register etc
like that if its messages I will create controller message and add all related methods in it so that my related functionality will be in a single group.
as far as the question of static pages you can also group them in a single controller if they can be a part of group.
you can also use codeigniter's caching technique for static pages so that your pages will load faster

How do I place a View belonging to a Plugin in regular View (CakePHP Howto)

I would like to get some input regarding the feasibility of the following scenario/design pattern:
I would like to insert a View from a Category Plugin (/category/categories/tree) into one of my application Views (/posts/edit/3) as if it is an CakePHP element.
The inserted View has a high level of functionality (sorting, adding, deleting, etc...) and therefore simply calling echo $this->element(); does not seem appropriate to me. That 'feels' more like a practice appropriate in situations where 'snippet'/lower level functionality is needed.
My question: is this possible in CakePHP, if so: how to do this? (just a rough outline of the way to go would suffice)
My first idea is to call an element from the plugin and use $this->requestAction(); from the element.
But as I said earlier is my association with elements one of little functionality/snippet. Using a controller method and its View 'feels' more appropriate. But I don't know how to 'call' a View within a View.
Main reason why I would want this:
full Controller functionality.
activate helpers based on Plugin requirements (this should be of no concern to the posts-controller)
beforeFilter and beforeRender of Plugin might be of use. For example: $this->set('modelName', $this->modelClass);
You could look at using view blocks. AFAIK, they are generally designed to help solve more complex view construction, like the problem you are considering here.
Or call a plugin element directly.

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).

Coding standards - Controller vs view

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.

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.

Categories