blob: d0f64e0c94c2a4641b78117903832002ddda0687 [file] [log] [blame]
Joël Coxf27bcf32011-08-22 22:29:06 +02001<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
3<head>
4
5<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
6<title>CodeIgniter Features : CodeIgniter User Guide</title>
7
8<style type='text/css' media='all'>@import url('../userguide.css');</style>
9<link rel='stylesheet' type='text/css' media='all' href='../userguide.css' />
10
11<script type="text/javascript" src="../nav/nav.js"></script>
12<script type="text/javascript" src="../nav/prototype.lite.js"></script>
13<script type="text/javascript" src="../nav/moo.fx.js"></script>
14<script type="text/javascript" src="../nav/user_guide_menu.js"></script>
15
16<meta http-equiv='expires' content='-1' />
17<meta http-equiv= 'pragma' content='no-cache' />
18<meta name='robots' content='all' />
19<meta name='author' content='ExpressionEngine Dev Team' />
20<meta name='description' content='CodeIgniter User Guide' />
21
22</head>
23<body>
24
25<!-- START NAVIGATION -->
26<div id="nav"><div id="nav_inner"><script type="text/javascript">create_menu('../');</script></div></div>
27<div id="nav2"><a name="top"></a><a href="javascript:void(0);" onclick="myHeight.toggle();"><img src="../images/nav_toggle_darker.jpg" width="154" height="43" border="0" title="Toggle Table of Contents" alt="Toggle Table of Contents" /></a></div>
28<div id="masthead">
29<table cellpadding="0" cellspacing="0" border="0" style="width:100%">
30<tr>
31<td><h1>CodeIgniter User Guide Version 2.0.2</h1></td>
32<td id="breadcrumb_right"><a href="../toc.html">Table of Contents Page</a></td>
33</tr>
34</table>
35</div>
36<!-- END NAVIGATION -->
37
38
39<!-- START BREADCRUMB -->
40<table cellpadding="0" cellspacing="0" border="0" style="width:100%">
41<tr>
42<td id="breadcrumb">
43<a href="http://codeigniter.com/">CodeIgniter Home</a> &nbsp;&#8250;&nbsp;
44<a href="../index.html">User Guide Home</a> &nbsp;&#8250;&nbsp;
45<a href="introduction.html">Tutorial</a> &nbsp;&#8250;&nbsp;
46News section
47</td>
48<td id="searchbox"><form method="get" action="http://www.google.com/search"><input type="hidden" name="as_sitesearch" id="as_sitesearch" value="codeigniter.com/user_guide/" />Search User Guide&nbsp; <input type="text" class="input" style="width:200px;" name="q" id="q" size="31" maxlength="255" value="" />&nbsp;<input type="submit" class="submit" name="sa" value="Go" /></form></td>
49</tr>
50</table>
51<!-- END BREADCRUMB -->
52
53<br clear="all" />
54
55
56<!-- START CONTENT -->
57<div id="content">
58
59
60<h1>Tutorial &minus; News section</h1>
61
62<p>In the last section, we went over some basic concepts of the framework by writing a class that includes static pages. We cleaned up the URI by adding custom routing rules. Now it's time to introduce dynamic content and start using a database.</p>
63
64<h2>Setting up your model</h2>
65
66<p>Instead of writing database operations right in the controller, queries should be placed in a model, so they can easily be reused later. Models are the place where you retrieve, insert, and update information in your database or other data stores. They represent your data.</p>
67
68<p>Open up the <dfn>application/models</dfn> directory and create a new file called <dfn>news_model.php</dfn> and add the following code. Make sure you've configured your database properly as described <a href="../database/configuration.html">here</a>.</p>
69
70<pre>
71&lt;?php
72class News_model extends CI_Model {
73
74 function __construct()
75 {
76 $this->load->database();
77
78 }
79}
80</pre>
81
82<p>This code looks similar to the controller code that was used earlier. It creates a new model by extending CI_Model and loads the database library. This will make the database class available through the <var>$this->db</var> object.</p>
83
84<p>Before querying the database, a database schema has to be created. Connect to your database and run the SQL command below. Also add some seed records.</p>
85
86<pre>
87CREATE TABLE news (
88 id int(11) NOT NULL AUTO_INCREMENT,
89 title varchar(128) NOT NULL,
90 slug varchar(128) NOT NULL,
91 text text NOT NULL,
92 PRIMARY KEY (id),
93 KEY slug (slug)
94);
95</pre>
96
97<p>Now that the database and a model have been set up, you'll need a method to get all of our posts from our database. To do this, the database abstraction layer that is included with CodeIgniter — <a href="../database/active_record.html">ActiveRecord</a> — is used. This makes it possible to write your 'queries' once and make them work on <a href="../general/requirements.html">all supported database systems</a>. Add the following code to your model.</p>
98
99<pre>
100function get_news($slug = FALSE)
101{
102 if ($slug === FALSE)
103 {
104 $query = $this->db->get('news');
105 return $query->result_array();
106
107 }
108 else
109 {
110 $query = $this->db->get_where('news', array('slug' => $slug));
111 return $query->row_array();
112
113 }
114
115}
116</pre>
117
118<p>With this code you can perform two different queries. You can get all news records, or get a news item by its <a href="#" title="a URL friendly version of a string">slug</a>. You might have noticed that the <var>$slug</var> variable wasn't sanitized before running the query; Active Record does this for you.</p>
119
120<h2>Display the news</h2>
121
122<p>Now that the queries are written, the model should be tied to the views that are going to display the news items to the user. This could be done in our pages controller created earlier, but for the sake of clarity, a new "news" controller is defined. Create the new controller at <dfn>application/controllers/news.php</dfn>.</p>
123
124<pre>
125&lt;?php
126class News extends CI_Controller{
127
128 function __construct()
129 {
130 parent::__construct();
131 $this->load->model('news_model');
132
133 }
134
135 function index()
136 {
137 $data['news'] = $this->news_model->get_news();
138
139 }
140
141 function view($slug)
142 {
143 $data['news'] = $this->news_model->get_news($slug);
144
145 }
146
147}
148</pre>
149
150<p>Looking at the code, you may see some similarity with the files we created earlier. First, the "__construct" method: it calls the constructor of its parent class (<dfn>CI_Controller</dfn>) and loads the model, so it can be used in all other methods in this controller.</p>
151
152<p>Next, there are two methods to view all news items and one for a specific news item. You can see that the <var>$slug</var> variable is passed to the model's method in the second method. The model is using this slug to identify the news item to be returned.</p>
153
154<p>Now the data is retrieved by the controller through our model, but nothing is displayed yet. The next thing to do is passing this data to the views.</p>
155
156<pre>
157function index()
158{
159 $data['news'] = $this->news_model->get_news();
160 $data['title'] = 'News archive';
161
162 $this->load->view('templates/header', $data);
163 $this->load->view('news/index', $data);
164 $this->load->view('templates/footer');
165
166}
167</pre>
168
169<p>The code above gets all news records from the model and assigns it to a variable. The value for the title is also assigned to the <var>$data['title']</var> element and all data is passed to the views. You now need to create a view to render the news items. Create <dfn>application/views/news/index.php</dfn> and add the next piece of code.</p>
170
171<pre>
172&lt;?php foreach ($news as $news_item): ?&gt;
173
174 &lt;h2&gt;&lt;?php echo $news_item['title'] ?&gt;&lt;/h2&gt;
175 &lt;div id="main"&gt;
176 &lt;?php echo $news_item['text'] ?&gt;
177 &lt;/div&gt;
178 &lt;p&gt;&lt;a href="news/&lt;?php echo $news_item['slug'] ?&gt;"&gt;View article&lt;/a&gt;&lt;/p&gt;
179
180&lt;?php endforeach ?&gt;
181</pre>
182
183<p>Here, each news item is looped and displayed to the user. You can see we wrote our template in PHP mixed with HTML. If you prefer to use a template language, you can use CodeIgniter's <a href="../libraries/parser.html">Template Parser</a> class or a third party parser.</p>
184
185<p>The news overview page is now done, but a page to display individual news items is still absent. The model created earlier is made in such way that it can easily be used for this functionality. You only need to add some code to the controller and create a new view. Go back to the news controller and add the following lines to the file.</p>
186
187<pre>
188function view($slug)
189{
190 $data['news_item'] = $this->news_model->get_news($slug);
191
192 if (empty($data['news_item']))
193 {
194 show_404();
195 }
196
197 $data['title'] = $data['news_item']['title'];
198
199 $this->load->view('templates/header', $data);
200 $this->load->view('news/view', $data);
201 $this->load->view('templates/footer');
202
203}
204</pre>
205
206<p>Instead of calling the <var>get_news()</var> method without a parameter, the <var>$slug</var> variable is passed, so it will return the specific news item. The only things left to do is create the corresponding view at <dfn>application/views/news/view.php</dfn>. Put the following code in this file.</p>
207
208<pre>
209&lt;?php
210echo '&lt;h2&gt;' . $news_item['title'] . '&lt;/h2&gt;';
211echo $news_item['text'];
212</pre>
213
214<h2>Routing</h2>
215<p>Because of the wildcard routing rule created earlier, you need need an extra route to view the controller that you just made. Modify your routing file (<dfn>application/config/routes.php</dfn>) so it looks as follows. This makes sure the requests reaches the news controller instead of going directly to the pages controller. The first line routes URI's with a slug to the view method in the news controller.</p>
216
217<pre>
218$route['news/(:any)'] = 'news/view/$1';
219$route['news'] = 'news';
220$route['(:any)'] = 'pages/view/$1';
221$route['default_controller'] = 'pages/view';
222</pre>
223
224<p>Point your browser to your document root, followed by <dfn>index.php/news</dfn> and watch your news page.</p>
225
226</div>
227<!-- END CONTENT -->
228
229
230<div id="footer">
231<p>
232Previous Topic:&nbsp;&nbsp;<a href="static_pages.html">Static pages</a>
233&nbsp;&nbsp;&nbsp;&middot;&nbsp;&nbsp;
234<a href="#top">Top of Page</a>&nbsp;&nbsp;&nbsp;&middot;&nbsp;&nbsp;
235<a href="../index.html">User Guide Home</a>&nbsp;&nbsp;&nbsp;&middot;&nbsp;&nbsp;
236Next Topic:&nbsp;&nbsp;<a href="create_news_items.html">Create news items</a>
237</p>
238<p><a href="http://codeigniter.com">CodeIgniter</a> &nbsp;&middot;&nbsp; Copyright &#169; 2006 - 2011 &nbsp;&middot;&nbsp; <a href="http://ellislab.com/">EllisLab, Inc.</a></p>
239</div>
240
241</body>
242</html>