Codeigniter writing a menu constructor - php

I've only just started learning CodeIgniter, so please excuse any misunderstandings I have.
I understand that the controller calls models and views. Views contain the HTML, models contain the database functionality etc.
I don't want to have to write code out to create a header menu, footer menu, side menu etc, in each of the controllers that import the menu structure into the view, so after some googling, it would look like it would be best to write a library in which my controllers can call to retrieve the type of menu they want.
My question is:
Would I place my database queries for retrieving the data to build each menu in the library itself, or would I delegate it to a model and call the model from the library? For the menu construction, I don't need to write to the database, just read the data it contains.
Many thanks

I never put any query directly in the library, as I believe that goes against the MVC that CodeIgniter intended.
I would aim to always make functions for simple database queries in the model, so that you may re-use them in various other portions. This allows you to return the data from what you need via the database when you require it. Which in turn allows you, in the library, to add additional caching or manipulate the data as it comes from the model.
I based that from 3 years of working in CI, and this little picture on this page: http://ellislab.com/codeigniter/user-guide/overview/appflow.html

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

Information from local DB and external source in one view

Situation:
The simplified situation is this: consider a blog that is build as an MVC project. The YII blog-example is fine for this, but the question is not framework specific: It is nothing special; you have a table with posts and a page build from:
a model (YII will give you a basic active-record setup)
a controller that for instance builds the index (list of all posts)
a view (or some views) that build the actual HTML in the end.
Now I have a working blog, but I also have an external source of information that I want to introduce to this same page: for example an RSS feed.
How do I add this new datasource?
Possible sollutions
To clarify what I am struggling with, here are some things I am considering
Make a new model that gets its information from both sources
Feels like the way of least resistance/work
It would need to sort the blogposts and RSS items by date
It might need to give some sort of flag about what kind of item it is (An RSS item might not have an author, but it does have a source).
The fact that above flag feels neccessairy makes me believe these should be 2 models.
Make a new model for the RSS and make a controller that combines the two sources and feeds it to a view that can handle both types of post
Something more complicated (maybe more framework specific), but the current view of a post is just one view for one post, and it gets repeated. Instead of one view that handles both types you might want not only a model, but also a view for your RSS, and a controller(?) that does all the mixing and matching?
Framework notes:
I'm using YII, but it's not really about YII. Ofcourse if something complicated is to be done I will have to implement it in YII, but it's about the design and the MVC pattern, not about where to put the ; ;D
u can hve something like this (I too use yii so the following code follows yii framework)
class XyzController extends CController
{
.
.
.
public function actionAbc()
{
.
.
.
$this->render('viewname',array(
'model1'=>$model1,//for posts frm table
'model2'=>$model2 //for rss feed
));
}
}
for better understanding try to render two separate views for each type of post inside the parent view "viewname"
If i had to do it, i would make a new controller for the view, and use two models.
I am very new to the mvc pattern, however from what i have gathered till now, it feels like any model should limit itself to only one data source. Also in addition to the CRUD operations, the "business logic" (if any) , should be included within that model. Business logic here would mean logic that applies to the data source pertaining to the web app, i.e the things that you have mentioned, like sorting RSS by date.
Create a controller that accesses these two models, to populate your view(s).
Finally the best way to organize these components/modules/parts of the mvc, with respect to Yii, depends on your app requirements, and ux.
Now, i think you should put this question in the programmers site also.
Hope this helps!
Edit: Not too sure where to put the sorting, controller or view.

PHP with OOP and MVC

Using PHP 5.x
Question, lets say I want to display results from a database. Lets say the last 30 stories from the database. Using OOP and MVC would the ideal setup be you have a class that connects to the db, a class that queries the database to get the information then a class that handles the display of the results and then a page that puts it all together?
So basically I would pass the db connection object to the class that gets me the story results from the database Then pass the story class object to the display class to build the view then pass that back to the view itself and echo out the value? Hopefully this makes sense, just trying to see if Im understanding this:
dbconnect_class.php
storyresults_class.php
storydisplay_class.php
Include all 3 into a page such as display_stories.php, which I believe is the controller in mvc, then run the code and display it in the view which would be in its basic form an include to a template file.
MVC meaning Model -> View -> Controller. In most of the frameworks the request comes to the Controller, the Controller asks the Model to retrieve the database results then the same Controller sends the results to the view in order to display them so that's the basic breakdown of a MVC application.
Don't pass the results object around. That will mean the display class needs to know the implementation within that class.
What you can do is let the controller get the results then pass the results to the display class.
You can make a data class that keeps the data in a suitable object which you can then pass to the display class.
However, this is just some general oop advice but for better mvc, you need to read on that. Some links have been provided by others.
Unless your using a template engine it would be very difficult to not write php code in a view file. At the company I work for, we have developed a set of UI components that allow us to bind data to a component in the controller and have that component render on the view, similary to how asp.net controls work.

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.

Zend Framework: right way to retrieve data from database

I am working on a project with zend framework and i need your advise on the right way to fetch data from the database.
Am making use of Zend_Layout to load my template. The appropriate view is then loaded into the template.
On the template, there is supposed to be a section that displays data from the database (e.g Categories). Since i am using one template, the data will be displayed on every page requested irrespective of the controller or action called.
I know its not a good practise to fetch the data from the template and it wouldn't be a good idea to fetch the data from each action executed. I dont know if the right thing to do is to use helpers to fetch the data from the database, but wouldn't that go against the whole idea of MVC.
You haven't mentioned the option of using a Model class to fetch the data. That's the "M" in MVC. :-)
A Model class is one that has an interface the View can use to request specific fragments of data. Inside the Model class, it may use a mix of using Zend_Db_Table methods, and also custom SQL queries (executed directly through Zend_Db_Adapter's query() method). Whatever works to get the data.
The point is that a Model encapsulates all the logic needed to supply data in a format the View can use.
See also
"An Introduction to Domain-Driven Design" at Microsoft.
"Domain-Driven Design" by Eric Evans.

Categories