Like many have said, just stick with plain PHP rather than having a template system that uses custom syntax. I once tried a 3rd party templating system (much like Smarty). I'll never use one again.
Use a good framework, such as CodeIgniter (a.k.a. CI, low learning curve, great docs, great overall) or Zend (high learning curve, enterprise level, great overall).
Since I've got more experience with CodeIgniter than I do Zend, I'll talk about it and how it works much like a templating system (minus the custom syntax... but you have the option to use it if you want).
CI follows (closer than most frameworks I've seen) the MVC (Model-View-Controller) design pattern. Essentially, your models interact with the database, your views are your templates, and your controllers are where all your business logic goes.
Here's a simplified example for a "template"-like implementation for viewing a blog article in CodeIgniter. Note that in this example I'm not using headers or footers simply for the sake of understanding this more easily. Also, I don't advise using short tags, but in this example I am for the same reason I'm not using headers or footers.
Your view (views/blog_article.php) might consist of
PHP Code:
<html>
<head>
<title><?=$page_title?></title>
</head>
<body>
<h1><?=$page_headline?></h1>
<?=$article_content?>
</body>
</html>
Your model (models/Blogmodel.php) might consist of
PHP Code:
class Blogmodel extends Model {
function Blogmodel()
{
// Call the Model constructor
parent::Model();
}
function get_article($article_id)
{
$this->db->where('article_id', $article_id);
$query = $this->db->get('articles');
if (!$query->num_rows()){
return FALSE;
}
return $query->result();
}
}
And your controller (controllers/Blog.php) might consist of
PHP Code:
class Blog extends Controller {
function index()
{
// Not used in this example.
}
function article($article_id)
{
$this->load->model('Blogmodel');
$article = $this->Blogmodel->get_article($article_id);
// Make sure the article exists.
if ($article === FALSE){
show_error("The article doesn't exist.");
}
$data['page_title'] = htmlentities($article->title); // becomes $page_title in your view
$data['page_headline'] = htmlentities($article->title); // becomes $page_headline in your view
$data['article_content'] = $article->article; // becomes $article_content in your view.
// - there ought to be no need for htmlentities
$this->load->view('blog_article', $data);
}
}
(Assuming we're using a server on localhost):
- http://localhost/blog/article/51 loads your Blog controller's article(51) method.
- Blog controller calls get_article(51) in the Blog model.
- Blog model returns article 51's row from the database.
- Blog controller takes bits of article 51's row and puts them into the $data array.
- Blog controller loads the blog_article view and injects the $data array into it, using its keys as variable names.
- The blog_article view is shown on your screen with the data.
Easy enough to follow?
Bookmarks