CAT | Tutorials
For the past few months, I’ve continued my work at my content management system. Since the start of the project in April 2009 the software has achieved quite some structure and features. All this with one goal in mind, to make things easier while developing websites. At this point, there only needs some minor functions to be added to the system such as ACL (Access Control List) and more advanced language support. When it comes to performance tweaks I’ve tried to minimize the loops and queries, and with only about 10 000 to 12 000 lines of PHP I’d say this CMS is quite lightweight. Also to maintain optimal performance for more high-traffic website I’m still thinking about improving the cache. Now to decide wether this is the CMS you want to use for your site you would of course want to have a look at it’s features. I’ll try to give a good overview but I might add some new features later on because I could have forgotten about some.
Structure
The aspect is the structure of the CMS, it’s not Module-View-Controller based but it’s something different. There are 8 different directories, but you will only use a few of them most of the time: admin, lang, cache, images, css, templates, modules and system. The first directory contains the admin area, it is expandable but you can do this within your module so there isn’t much need to go in there. Then we have the lang and cache directories. These are maintained by the system and store system files. The images and css directories are just shared directories to be used amongst different templates e.g. error css. I might move that to one single html folder. The system directory contains functions, classes, configuration, imports, the router and database class. Only some of these files are imported by default because they are necessary to operate succesfully. Setting up your template is very easy. It doesn’t require a lot of changes, you just place some {TAGS} such as {MODULE} and {TITLE} which are automaticly filled in.
The module tag is controlled by the modules, these form the core of your application. They load the HTML files necessary to generate the content for the pages. The PHP and HTML is seperated from eachother by my own template engine. An example of a module could be news. This module will have an html, maybe xml (for ajax and rss feeds) directories. And a control.php file. I will go into this more deeply later on since there are also two different types of modules: background processes and display modules. Only one display module can be called at a time and the various background processes may run but these are often very simple such as a log to keep record of users. Now what a display module does is, when an action is called the php will process it. It will import the HTML file and put it on the {MODULE} tag and the html file may also contain its own user-defined tags which may be used to put php variables into or to place another html file. PHP can only be used in the html when it is written with a .phtml extension. The template engine will parse this file when it recognises this extension. So this makes a very clear distinction between PHP and HTML while giving the programmer the freedom of still beeing able to use PHP in the HTML if needed. There is no need to learn a custom template language.
Features
Now that you have a basic overview of the structure a good overview of features may be handy.
- Templates: seperate PHP from HTML
- Support for multiple languages
- Router for when you have mod_rewrite enabled, but this is not necessary
- Advanced Caching
- URL and Parameter validation on top-level.
- Custom Error Handling
- Database class for MySQL
- Security for MySQL Injections
- Admin area
- User management
- Access Control List
- RSS Feed Generator
- Support for AJAX Requests
- Custom Template Engine
- Extensions for Admin Area
- Multiple templates (public and private)
I’m sure I have forgotten about some functions, but these are the main functions that the system offers you =). Now wether I will make it openSource is still not sure.
Example of a News Module
Ok suppose we would like to create a module that serves news articles. We will create a directory ‘news‘ in modules. This module will contain a html folder with the HTML for the Article page and the HTML for each article. So we create ‘news.html’ and ‘article.html‘. Now in news module we will also create a ‘display.php‘ file that will handle the actions. So basically what we have got now should look like:
First of all we will have to tell the system to allow the request. So we open up the router and add this line.
This will tell the Router to allow News and to only accept parameters from article with a numeric value. You can specify extra options for more advanced url and parameter validation but we won’t go into that right now.
Router::setURL('/News/article/*');
Now we will supply some HTML to work with. An example of what ‘news.html‘ could look like is:
<h1>News Page</h1>
<div id="articles">{ARTICLES}</div>
Second we will create the HTML for the ‘article.html‘.
<div class="article-preview">
<h2>{TITLE}</h2>
<p>{CONTENT}</p>
<a href="/news/article/{ID}">Read More</a>
</div>
Ok enough HTML written! Time to make this code work =). We will now go into the ‘display.php‘:
$db->setQuery('SELECT `title`, `content`, `id` FROM `@__news` LIMIT 5');
$db->fetchList('Articles');
$tpl->loadHTML('news', 'Module');
foreach($Articles as $Article){
$tpl->loadHTML($html = 'article', $tag = 'Articles', true);
$tpl->Replace($Article);
}
$tpl->Delete('Articles');
Only a few lines to make the entire news article work! Now let me explain this line by line because it may seem complicated at first sight. First we load the articles from the database. The @__ is needed if you wish to make use of a table prefix. The results are loaded into the variable $Articles. Then we load in the HTML file and place it where the {MODULE} tag is located. Now this makes the tags in ‘news.html‘ available for use to the template engine. And then it will go through each article one by one and while we do this we will load in ‘article.html‘ each time and replace the tags inside them. And finally we will have to delete the remaining {ARTICLES} tag because we have specified a third parameter true in the loadHTML function which puts the {ARTICLES} tag back in place for use. Making it available for the second article and so on.
The replace function may be unclear right now, but what it does is. It sees that $Article is an array and for each key it tries to find an according tag and then it puts the values of the key on the location of the tag.
Another method to do this would have been:
$tpl->Replace( array( 'title' => $Article['title'], 'content' => $Article['content'] ) );
But the example is just to show what kind of magic into some functions =). I hope you have enjoyed reading through this quick introduction. I hope it may provide you with some insight it the possibilities of using a cms. The reason why I think this CMS might be interesting is because it isn’t really based on one model out there, it is more a unique combination of what I thought to be the best solution I encountered each time while programming this system.
Today we’re going to make a simple script that logs all of your visitors and puts it into a database. I will comment every step so you will understand how it works. For newbies who don’t understand PHP yet check out the first tutorial.
<?php
$mysql_connect = mysql_connect('host', 'user', 'password') or die("We could not connect to the MySQL server.");
// This is simple a connection to the database.
// I'll provide some details on how to construct the table inside the DB later.
$mysql_database = mysql_select('database') or die("We could not select the database.");
// Just pick a database where u made your 'visitor' table
// Note: or die(mysql_error()); Is very handy in most cases. It returns a very specific error.
// So now we have the database connection
$user = array();
$user['ip'] = $_SERVER['REMOTE_ADDR'];
$user['browser'] = $_SERVER['HTTP_USER_AGENT'];
$user['page'] = $_SERVER['PHP_SELF'];
// We now create an array and we fill in keys that contain values.
// These values are generated by PHP when a user runs your script (opens a page)
// These values then get put in the $_SERVER array and you can simply fetch them from there.
$insert = mysql_query("INSERT INTO `visitors` (`ip`,`browser`,`page`)VALUES($user['ip'], $user['browser'], $user['page']) ") or die(mysql_error());
// This query inserts all the information we just gathered into our table.
?>
Now some info on how to create this table
The table name : visitors
Fields: 4
First field is the : visitor_id it is the Primary field and it auto increments and an Integer
This means that it simply starts from 0 and always goes up , its a unique id for each field
It helps a lot when you need to select one of these to set an ip to banned for example if you have such a column
Second field : visitor_ip VARCHAR 255 or something
Third field : browser VARCHAR 355
Fourth field : page VARCHAR 35
You can easily set up tables and databases using PHPMyAdmin
1.Introduction
What is PHP? PHP is a server-side programming language. This means it processes a certain script to create a dynamic output in HTML. In most cases PHP is used together with some sort of Database such as MySQL. For example when a user clicks on the news page. The News.php script can ask the 10 latest news articles from the MySQL database. And while it is requesting this information it can sort it out in HTML tables with a heading, comment button etc. When you’re just using HTML you can’t do this and your information will always be static. Now let us take a quick view at how a PHP script may be.
<?php
echo("Hello Visitor");
?>
This will just output the string : Hello Visitor. As you can see the PHP script starts with <?php and ends with ?>. This tells the server when the PHP module will have to start processing the script and when the normal static HTML begins ( after the ?>). Echo is the function. Functions can handle information the way you want them to deal with it. But we’ll come to that later. As you can see we tell the script that we’re processing a string by placing it between the ” ” quotes. And each function ends with a ; character. Let us continue with variables.
2.Variables
<?php $variablename = "content"; echo $variablename; ?>
This script will output : content . Variables are used to store information. Just temporary of course. After the script is done at the very very end. When the client is looking at the page with all the processed information. At this part the PHP script will automaticly remove these variables. This is an automatic process wich is called the ‘Garbage-collector’. But you can delete variables yourself if you like. You can do it this way.
<?php unset($variable); ?>
3.Cookies
This is mostly advised when the variable holds a large amount of data. So you can unset it when you no longer need it. But when using normal scripts you don’t need to worry about it. Ok so how can you store information permantently? Through databases, with sessions or with cookies! Yes cookies =D. Cookies are stored in your browser, but of course the visitor needs to allow the cookies to be stored in his settings. Thats why you can’t login on sites when you don’t store cookies. For example when you login on some site. And your pass and username are correct the script normally creates a cookie with the name ‘username’ and as value your name. And a cookie ‘password’ and your password. And each time you go to a page the script checks if you have a cookie username so it recognises you as logged in. You can set cookies like this.
<?php
setcookie("username", "vincent"); // for example
?>
4.IF and ELSE statements
This is how you set a cookie. The text after the // is seen as a comment and the PHP script simply ignores this. Now you know what functions can do. PHP has a lot of functions preprogrammed wich you can find on www.php.net As for the basics of PHP i’m going to explain you another aspect. After this you will understand the very basics and you will be set to learn a lot more in the documentation or with other tutorials.
The IF and ELSE statements. These are so handy. Like suppose you want to see if a user is logged in.
<?php
$user = $_COOKIE['username'];
if($user){
echo("Welcome $user");
}
else{
echo("Welcome Guest");
}
?>
The user variables gets the information from the cookie ‘username’. If it exists and if there is information in the cookie. It will welcome the user and display its username. Otherwise it will welcome the guest.
The actions that will occur when the statement is true are always located between the { } brackets.
So that was my tutorial about the basics of PHP explained. I hope you have learnt a lot. And if you have any more questions don’t hesitate to comment below and ask your question =).
