summaryrefslogtreecommitdiffstats
path: root/user_guide/tutorial/news_section.html
blob: cf3377ff9b9068c526b12ff0c6447e71ac636ce2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>CodeIgniter Features : CodeIgniter User Guide</title>

<style type='text/css' media='all'>@import url('../userguide.css');</style>
<link rel='stylesheet' type='text/css' media='all' href='../userguide.css' />

<script type="text/javascript" src="../nav/nav.js"></script>
<script type="text/javascript" src="../nav/prototype.lite.js"></script>
<script type="text/javascript" src="../nav/moo.fx.js"></script>
<script type="text/javascript" src="../nav/user_guide_menu.js"></script>

<meta http-equiv='expires' content='-1' />
<meta http-equiv= 'pragma' content='no-cache' />
<meta name='robots' content='all' />
<meta name='author' content='ExpressionEngine Dev Team' />
<meta name='description' content='CodeIgniter User Guide' />

</head>
<body>

<!-- START NAVIGATION -->
<div id="nav"><div id="nav_inner"><script type="text/javascript">create_menu('../');</script></div></div>
<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>
<div id="masthead">
<table cellpadding="0" cellspacing="0" border="0" style="width:100%">
<tr>
<td><h1>CodeIgniter User Guide Version 2.1.0</h1></td>
<td id="breadcrumb_right"><a href="../toc.html">Table of Contents Page</a></td>
</tr>
</table>
</div>
<!-- END NAVIGATION -->


<!-- START BREADCRUMB -->
<table cellpadding="0" cellspacing="0" border="0" style="width:100%">
<tr>
<td id="breadcrumb">
<a href="http://codeigniter.com/">CodeIgniter Home</a> &nbsp;&#8250;&nbsp;
<a href="../index.html">User Guide Home</a> &nbsp;&#8250;&nbsp;
<a href="index.html">Tutorial</a> &nbsp;&#8250;&nbsp;
News section
</td>
<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>
</tr>
</table>
<!-- END BREADCRUMB -->

<br clear="all" />


<!-- START CONTENT -->
<div id="content">


<h1>Tutorial &minus; News section</h1>

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

<h2>Setting up your model</h2>

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

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

<pre>
&lt;?php
class News_model extends CI_Model {

	public function __construct()
	{
		$this->load->database();
	}
}
</pre>

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

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

<pre>
CREATE TABLE news (
	id int(11) NOT NULL AUTO_INCREMENT,
	title varchar(128) NOT NULL,
	slug varchar(128) NOT NULL,
	text text NOT NULL,
	PRIMARY KEY (id),
	KEY slug (slug)
);
</pre>

<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">Active Record</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>

<pre>
public function get_news($slug = FALSE)
{
	if ($slug === FALSE)
	{
		$query = $this->db->get('news');
		return $query->result_array();
	}
	
	$query = $this->db->get_where('news', array('slug' => $slug));
	return $query->row_array();
}
</pre>

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

<h2>Display the news</h2>

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

<pre>
&lt;?php
class News extends CI_Controller {

	public function __construct()
	{
		parent::__construct();
		$this->load->model('news_model');
	}

	public function index()
	{
		$data['news'] = $this->news_model->get_news();
	}

	public function view($slug)
	{
		$data['news'] = $this->news_model->get_news($slug);
	}
}
</pre>

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

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

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

<pre>
public function index()
{
	$data['news'] = $this->news_model->get_news();
	$data['title'] = 'News archive';

	$this->load->view('templates/header', $data);
	$this->load->view('news/index', $data);
	$this->load->view('templates/footer');
}
</pre>

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

<pre>
&lt;?php foreach ($news as $news_item): ?&gt;

    &lt;h2&gt;&lt;?php echo $news_item['title'] ?&gt;&lt;/h2&gt;
    &lt;div id="main"&gt;
        &lt;?php echo $news_item['text'] ?&gt;
    &lt;/div&gt;
    &lt;p&gt;&lt;a href="news/&lt;?php echo $news_item['slug'] ?&gt;"&gt;View article&lt;/a&gt;&lt;/p&gt;

&lt;?php endforeach ?&gt;
</pre>

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

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

<pre>
public function view($slug)
{
	$data['news_item'] = $this->news_model->get_news($slug);

	if (empty($data['news_item']))
	{
		show_404();
	}

	$data['title'] = $data['news_item']['title'];

	$this->load->view('templates/header', $data);
	$this->load->view('news/view', $data);
	$this->load->view('templates/footer');
}
</pre>

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

<pre>
&lt;?php
echo '&lt;h2&gt;'.$news_item['title'].'&lt;/h2&gt;';
echo $news_item['text'];
</pre>

<h2>Routing</h2>
<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>

<pre>
$route['news/(:any)'] = 'news/view/$1';
$route['news'] = 'news';
$route['(:any)'] = 'pages/view/$1';
$route['default_controller'] = 'pages/view';
</pre>

<p>Point your browser to your document root, followed by <dfn>index.php/news</dfn> and watch your news page.</p>

</div>
<!-- END CONTENT -->


<div id="footer">
<p>
Previous Topic:&nbsp;&nbsp;<a href="static_pages.html">Static pages</a>
&nbsp;&nbsp;&nbsp;&middot;&nbsp;&nbsp;
<a href="#top">Top of Page</a>&nbsp;&nbsp;&nbsp;&middot;&nbsp;&nbsp;
<a href="../index.html">User Guide Home</a>&nbsp;&nbsp;&nbsp;&middot;&nbsp;&nbsp;
Next Topic:&nbsp;&nbsp;<a href="create_news_items.html">Create news items</a>
</p>
<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>
</div>

</body>
</html>