Chapter 3. Listing posts

A page in Atomik is made of two files: the first one is dedicated to the business logic, it is called an action. The second one is called a view and holds the presentation code, in most case HTML.

Actions are located in the app/actions folder and views in the app/views folder. For example, for a page named home, we would need a home.php file in the actions folder and a home.phtml file in the views folder.

Note

Both files are not mandatory when creating a page. At least one of them has to exist.

The default page is named index. We will list posts on this one. We'll first need to retreive posts from the database. In the action file (app/actions/index.php), add the following lines:

			
<?php
$posts = Atomik_Db::findAll('posts');
		

That's all we need to retreive all posts from the database! The Atomik_Db::findAll() method takes as first argument a table name and we specified posts. It returns a PDOStatement object with all the returned rows.

Variables defined in the action are automatically available in the view. Thus, we can iterate through the $posts variable to list our posts.

			
<h1>Blog</h1>
<ul>
	<? foreach ($posts as $post): ?>
		<li><?= $post['title'] ?></li>
	<? endforeach; ?>
</ul>
<a href="<?= Atomik::url('add') ?>">Add a new post</a>
		

Note

PHP short open tags will be used in code listing. Check your PHP configuration to see if it is supported on your server.

As you can see this listing also uses PHP's alternative syntax. This is advice when adding PHP code into views as it makes them clearer.

The add page will be described in the next chapter.

Now, navigate to http://localhost. Don't worry if nothing show up, we havn't created any post yet.