Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

Friday, May 30, 2008

CakePHP: Working with View

In the last article, I wrote a 'Hello World' program.
class TestersController extends Controller{
  var $uses=null;
  var $autoRender=false;
  function sayHello(){
    echo 'Hello, CakePHP!';
  }
}
?>

But it has a problem. According to MVC pattern, a controller shouldn't be used for displaying. However, that example uses 'echo' statement in the controller. It is a bad style. In MVC, view is used for showing data. So today I will write something about how to use view to display a page.

A view is usually a file containing much HTML but bit of PHP code. In CakePHP, a controller is associated with some views, depending on its name. For instance, the controller "Testers", its class name is "TestersController" and it must be located in app/controllers/testers_constroller. Its view must be located in app/views/testers/. Each action can have its view. For example, the view of TesterConstroller::sayHello() is app/views/testers/say_hello.thtml. No more to say, let's have a look at the view's content (say_hello.thtml):
Hello, !

You see, it's very simple, just displays a variable $name. Now the questing is: how to pass the variable from the controller? The answer is "set()". Modify the controller class above:
class TestersController extends Controller{
  var $uses=null;
  function sayHello(){
    $this->set('name','Woody');
  }
}
?>
Here, $this->set('name','Woody') set the variable $name. You see, now the controller don't contain output statement. It just set some variables and pass them to a view (because I removed "$autoRender=false", CakePHP will execute app/views/testers/say_hello.thtml). Now open http://localhost/cake/testers/sayHello (suppose your CakePHP project is in WEBROOT/cake/ directory), you will see "Hello, Woody!".

But there's is another problem. The result contains some more we don't want, like the big title "CakePHP Rapid Development" and the CakePHP's logo on the bottom right. Why is it? The answer is "layout". A layout is similar to a view. Considering a real website. It may contain many pages. But all the pages have some same elements, such as top banner, header text, CSS, etc. We don't need to put these things into all views. Just need layout once. Layout is used for sharing common view elements and it is usually a completed HTML file. Since we haven't create our layout, CakePHP will use its own.

Now let's create a default layout. Its file path is "/app/views/layouts/default.thtml". The content:
<html>
<head>
<title><?php echo $title_for_layout; ?></title>
</head>
<body>
<h1>Learn CakePHP</h1>
<?php echo $content_for_layout; ?>
</body>
</html>
And then change the sayHello action into:
function sayHello(){
  $this->pageTitle='This is the title for the layout.';
  $this->set('name','Woody');
}
Then run the action and check the brower's title bar.

How does a controller get data from a view?

Usually, views contain some forms to get users' input. According to MVC, the input data will be passed to controllers. Since it needs more examples, I plan to write something about it in some day in the future.

Monday, May 26, 2008

XAMPP is The Best Choice for Programmers

XAMPP is an open source suit of Apache, MySQL, PHP/Perl. To many people, installing Apache, MySQL and PHP is difficult. XAMPP integrates them into one package. Moreover, it can run on many operating systems, such as Linux, Windows, Mac OS X and Solaris. With XAMPP, you don't need to edit any configuration file, just unpacking it, even no need to install, you can run your Apache web server with PHP and MySQL support.

Why did I say the XAMPP is appropriate for Programmers? Here are some reasons. First, XAMPP can run on many platforms, you needn't change your program or configuration files if you want to change the operating system. Second, the default configuration of XAMPP is convenient for debug program. So it is not appropriate for the final products. Third, XAMPP provides some add-ons to extend its function. Now you can integrate Perl and Tomcat into XAMPP. Besides, XAMPP contains much PHP extensions, for example, libjpeg, libpng, gdbm, zlib, expat, Sablotron, libxml, etc.

The current version of XAMPP is 1.6.6a. The Windows distribution contains:
  • Apache HTTPD 2.2.8 + Openssl 0.9.8g
  • MySQL 5.0.51a
  • PHP 5.2.5
  • PHP 4.4.8
  • phpMyAdmin 2.11.4
  • FileZilla FTP Server 0.9.25
  • Mercury Mail Transport System 4.52
Do you want a try? Click here.

Update: I received the comments. I agree with them, too. I think a good PHP programmer should know how to configure Apache, PHP and MySQL, etc. I think XAMPP is the best because it makes the work very easy. So it can save much time. Certainly, unstanding how they work is necessary for a good programmer.

Thursday, May 15, 2008

CakePHP: Hello World!

CakePHP is an MVC framework. Model, view, controller are the main components. Generally speaking, the model is an object and is used to operate database. You should employ it to communicate with database, like inserting, deleting, querying. The view is as its name. It is used to display the result. Usually it contains lots of HTML but few PHP code. The controller is employed to handle HTTP requests and do some logic. The controller is central in an MVC pattern. It calls the model to get data from database, then do some work, and sends the result to a view to display.

Let's have a look at CakePHP. I will use CakePHP to write a "hello world" program. My CakePHP is located in D:\xampplite\htdocs\cake. In it there are four directories: app, cake, docs, vendors. "app" is the working directory where we should save our code. Now let's write some codes.

<?php
class TestersController extends Controller{
var $uses=null;
var $autoRender=false;
function sayHello(){
echo 'Hello, CakePHP!';
}
}
?>


As you see, the name of the controller class is TestersController. i.e. The controller's name is Testers. According to the CakePHP convention, the controller's name should be plural form. You must save it as "testers_controller" in app\controllers so that CakePHP can find the controller class.

Before you run it, please make sure that mod_rewrite is on. Check your Apache http.conf, find the line like "LoadModule rewrite_module modules/mod_rewrite.so". If it is commented, just uncomment it (remove "#"). Now start or restart (if you modified http.conf) Apache server. Enter http://localhost/cake/testers/sayHello in your browser's address bar. You can see the result if no problem happens:
cakephp_helloworld


Now let me explain the program in detail. In the TestersController class I define two variables: $uses and $autoRender. $uses specifies which models the controller can use. I set it "null" so that it don't use any model. If I omit it, CakePHP will look for the model "Tester" automatically. That will produce an error because I haven't created the model class. See below:
cakephp_missing_model

$autoRender=false makes CakePHP not search for the view for TestersController::sayHello() because I haven't create the view. If it is omitted, a missing view error will occurred.

The function sayHello() is called "action" in the controller class. That's to say, A controller may have several actions to handle different tasks, and each action is just a function in the controller class. Controllers and actions are mapped into URL. For example, when we open http://localhost/cake/testers/sayHello, CakePHP will find TestersController class and execute sayHello() function automatically. We can call any action by typing different URLs.

That's all. In this example I just used controller to write a "hello world" program. It is just beginning. There are many features in CakePHP. I hope my articles will be helpful for you.

Update: To simplify the example, I use "echo" statement in the controller. That's a bad style. In fact, we should use "view" to show data or result. If you are interested, see Working with View.

Wednesday, May 14, 2008

Start to Learn CakePHP

Choosing a proper PHP framework is difficult (see this). Fortunately, at last, I make a decision that I'm going to learn CakePHP at first. CakePHP is small and easy to use. And there are many free tutorials on the Internet. So I think it is not hard to get help. Also, I used FleaPHP which is developed by a Chinese programmer half a year ago. I feel CakePHP is similar to FleaPHP, and obviously CakePHP is much better and more powerful. It seems to be easier to learn than Symphony or Zend Framework for me.

I downloaded it just now and installed it on my computer according to its manual. It's very simple, just unpack the zip file into a sub-directory located in www root, for example, "cake". Then run your Apache, enter "http://localhost/cake/" in your browser's address bar. You will see a welcome page. If you don't see it, please refer to the manual book. I used XAMPP on Windows, a suit of Apache, PHP and MySQL. CakePHP runs well on it.

Now it is 22:50. I'm going to sleep. I will learn CakePHP formally next day and write some notes here.

Tuesday, May 13, 2008

Looking for a PHP Framework

MVC is an import design pattern for web development. I think the easiest way to apply MVC with PHP is to use an appropriate framework. So I have been looking for an appropriate PHP framework for quick development these days. The diffficult thing is that there are too many choices. It seems that the most widely used are Zend Framework, Symphony and CakePHP. I think CakePHP is better because it is lightweight. Symphony has lots of documents, especially it supports AJAX well, but it is said it's hard to learn. Zend Framework is too fat so I doubt if it is convenient to learn and to use.

Also, I found PRADO PHP Framework. It is component-based and event-driven. Event-driven seems interesting. The code style is similar to JSP and ASP.NET.

Which framework do think is best? Maybe I shouldn't waste much time to choose a framework. But unlike JSP, Struts, Hibernate and Spring is enough for almost any web application, frameworks in the world of PHP are too many. That's hard to choose one to start to learn.

Any suggestions?

Monday, May 12, 2008

Blogging Tool: Windows Live Writer

Windows Live Writer is a blog writing tool. It provides a powerful editing environment, like a simple MS Word. You can use it to write on your own computer and after finishing a post just click the publish button. The post will be published.

Since I'm living in China and China blocks all the blogs on blogspot.com sometimes (may be always), so Windows Live Writer cannot connect to the Internet. That's boring.

Here is a screenshot:

Windows Live Writer

PS: Windows Live Writer can only run in Windows XP or above and need .net framework 2.0 support.

Sunday, May 11, 2008

Introduction to Regular Expression

Regular expression is a powerful tool for handling string. For example, it is often used to validate Email, find all URLs in an HTML file, etc. Many programming languages support regular expresiong, such as Java, Python, PHP. Some languages, like C and C++, don't support it though, you may find some libraries (such as Boost) to handle regular expression instead. In this section, I don't want to introduce how to use regular expression in each programming language. In fact, regular express is in common use. Now let's look at the syntax of regular expression. To see clearly, I use '/.../' to describe a regular expression and '...' to describe a normal string. The symbol '~' means 'match'.

Matching strings is the goal which regular expression is designed for. For example, '/ea/' can match all strings contain the characters 'ea', such as 'please', 'reason', 'easy'. The dot '.' can match any character. When some characters are put in '[]', it means 'or'. See below:
'/[bcm]at/' ~ 'bat', 'cat', 'mat', but not 'bmat'. i.e. characters in [] can be matched only once.
'/[a-z]/' matches all strings that contain lower letter. Here, the minus symbol '-' means 'to'. It describes a range.

Let me take more useful examples:

How to validate an IP address? We know that IP address can be expressed as xxx.xxx.xxx.xxx. Here, 'x' stands for a digit. We can use '/([0-9]{1,3}){4}/' to match IP addresses. However, there are some special characters need to be explained. First, '[0-9]{1,3}' means a digit can be repeated one to three times. i.e. it (the subexpression) can match '1','12','123', etc. Second, the parentheses mean 'a group', because we want the subexpression '[0-9]{1,3}' be applied four times. Up to now you know that brackets specify the repeat times. Moreover, {1,} means repeat one or more times. So you can use '/[1-9][0-9]{0,}/' to match any positive integer.

How to validate an email address? An email address consists of an account name, a symbol '@' and a domain name. It's a little harder work. Let's see the regular expression first: '/^[a-zA-Z0-9\-.]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-.]+$/'. It contains more special characters. the symbol '^' out of [] means it can one match the head of the string. For example, '/^ea'/ matches 'easy' but not 'reason'. By the way, '^' in the [] has another meaning. I will explain it after a while. The dot '.' in [] doesn't stand for any character. In details, if a dot is the first or the last character in [], it just stands for a dot '.'. The plus symbol '+' means 'repeat one or more times'. It is equivalent to {1,}. There is another symbol '*' similar to '+', means 'repeat zero or more times'. The last symbol in the regular express '$', has the opposite meaning of '^'. It means that it matches the tail of the string only. For example, '/ing$/' mathes 'doing', 'seeing', but not 'surprisingly'.

Just now I said '^' in the [] has another meaning. What it it? It means 'not contain'. For example, '/[^0-9]/' can match any non-digit character.

OK, it is just an introduction to regular expression. Regular expression is very powerful tool and it can be very complex. Even you can use it to parse programming code. Now many text editor provides syntax highlight function. It can be implemented with regular expression. It is necessary skill to a programmer.

Wednesday, May 7, 2008

The Difference Between mysql_fetch_array() And mysql_fetch_assoc()

Getting data from MySQL with PHP is very convenient. But I found most of PHP beginners don't know the difference between two MySQL functions: mysql_fetch_array() and mysql_fetch_assoc(). If you don't understand the two functions, you always come up against such problem: why can't I see the result from MySQL?

Suppose we have a database called 'test' and it has a table called 'members' which stores some members' information. The goal is to fetch all the members' information. Consider such code below:

$conn=mysql_connect('localhost','root','');
$mysql_select_db('test');
$rs=mysql_query('SELECT * FROM members');


Then $rs is an array that stores all personal information. You can use mysql_fetch_array() or mysql_fetch_assoc() to fetch each row by calling the function repeatedly. Consider:

while ($row=mysql_fetch_array($rs,MYSQL_NUM)){
// ...
}

Here $row is a normal array (integer-indexed array). You cannot get data with $row['name'], $row['birthday'], etc. You must use integer as the index, e.g. $row[0], $row[1]... How to get an associative array? You need to set the second parameter of mysql_fetch_array(). MYSQL_ASSOC tells mysql_fetch_array() to return an associative array. See below:

while ($row=mysql_fetch_array($rs,MYSQL_ASSOC)){
// ... here you can use $row['name'], $row['birthday']...
}


mysql_fetch_array($rs,MYSQL_BOTH) equals to mysql_fetch_array($rs). There's no need to use MYSQL_BOTH, so we often omit it.

So you can use two methods to fetch data by specifying the second parameter to MYSQL_BOTH or omitting the second parameter. Then both of the styles, $row[0] and $row['name'], are available.

But where's mysql_fetch_assoc()? It seems not useful. Right. mysql_fetch_assoc($rs) is equivalent to mysql_fetch_array($rs,MYSQL_ASSOC). Obviously, when you need to an associated array (string-indexed array) only, mysql_fetch_assoc() is more convenient. By the way, mysql_fetch_assoc doesn't have the second parameter. It can only return associative array so it needs less memory space to store the result array.

Friday, May 2, 2008

Running PHP In The Console

When you test a small PHP script, you need run a web server, such as Apache, then open a browser to see the result. How dirty the work is! The simple method to run a PHP file is to call PHP interpretor in the console.

For Unix/Linux, the only thing you need to do is enter such line in the console:

php -f your_php_file


For Windows, the best way to run a PHP script is to call PHP interpretor from a text editor or IDE. I like SciTE, a powerful text editor for programming. Open html.properties from options menu, then add these lines in the bottom:

PHP_Bin=D:\xampplite\php
command.go.$(file.patterns.php)=$(PHP_Bin)\php.exe -f "$(FileNameExt)"
command.compile.$(file.patterns.php)=$(PHP_Bin)\php.exe -l "$(FileNameExt)"


"PHP_Bin" specifies where the PHP interpretor is. After doing that, when you open a PHP file next time, you can run it in SciTE just select "Tools" -> "Go" or press F5. If you select "Tools" -> "Compile" or press Ctrl+F7, PHP interpretor doesn't run the script but check syntax instead.

Thursday, May 1, 2008

What's BBCode?

BBCode is short for "Bulletin Board Code". It is a markup language which is similar to HTML and it is widely used on forums. So it is also called "forums code". Many forums don't accpte HTML code so you can't use HTML to format your text. Most of forums support BBCode. For example, if you want to use bold text, just type "It is [b]bold text[/b]." then the program of the forum changes it into HTML code "It is <b>bold text</b>.".

Below are most useful BBCode markups:
  • [b]bolded text[/b]: bolded text
  • [i]italicized text[/i]: italicized text
  • [u]underlined text[/u]: underlined text
  • [url]http://deepbluespaces.blogspot.com/[/url]: http://deepbluespaces.blogspot.com/
  • [url=http://deepbluespaces.blogspot.com/]Deepblue Spaces[/url]: Deepblue Spaces
The normal method to parse BBCode is "Regular Expression" which is widely used to handle string problem. I plan to write something about regular expression in a few days.

Sunday, April 27, 2008

Using PHPMailer of WordPress to Send Email

In PHP langauge, the usage of the mail() function is too complex. Besides, when you are working on Windows operating system, it is diffcult to find an appropriate "sendmail" program. But if you work on Linux or Unix, mail() function may work better, althought its arguments are too complex.

I read the source code of WordPress this afternoon and found two classes for sending mail -- PHPMailer and SMTP. WordPress uses PHPMailer to send new password when you lost your password. Moreover, PHPMailer supports multiple sending method, such as PHP function main(), Qmail, remote SMTP server or other "sendmail" programs. Especially SMTP server. So far, there are fewer and fewer anonymous SMTP servers on the Internet, most of them need authentication. SMTP class make these things simple and easy. When you let PHPMailer use remote SMTP server to send Email, PHPMailer will use SMTP to connect to the remote server to accomplish the task.

Now let's see how to use PHPMailer to send your Email.

Firstly, you need to copy class-phpmailer.php and class-smtp.php from wp-includes directory of WordPress to your working directory. Then make a new PHP file in your working directory to enter codes. See below:

<?php
include ('class-phpmailer.php');
include ('class-smtp.php');

$mail=new PHPMailer();

// Let PHPMailer use remote SMTP Server to send Email
$mail->IsSMTP();

// Set the charactor set. The default is 'UTF-8'
$mail->CharSet='UTF-8';

// Add an recipients. You can add more recipients
// by using this method repeatedly.
$mail->AddAddress('xxxxxxx@gmail.com');

// Set the body of the Email.
$message='This Email is sent by PHPMailer of WordPress';
$mail->Body=$message;

// Set "From" segment of header.
// For 163.com Email service, it must be the same
// with your account.
$mail->From='xxxxxxx@163.com';

// Set addresser's name
$mail->FromName='Wang Jinbo';

// Set the title
$mail->Subject='Test Mail';

// Set the SMTP server.
$mail->Host='smtp.163.com';

// Set "need authentication".
$mail->SMTPAuth=true;

// Set your username and password.
$mail->Username='xxxxxx';
$mail->Password='xxxxxx';

// Send Email.
$mail->Send();
?>


Here I described how to use PHPMailer to send Email. Of course, there are other options in PHPMailer class. You can understand the usage of it by reading the source code and trying it in person.

A Good Programming Forum

Last night I found a good programming forum, CodeCall Programming Forum. I feel all the people there are friendly and enthusiastic. There are many topics on all programming languages almost, from C++ to web development. I think I can learn more on that forum and help more people. I like the atmosphere of the forum. So I have introduced it to my friends, I hope she will enjoy the atmosphere.

By the way, introduce myself. I'm a college student learning software technology. I took part in some algorithm contest in high school. So far, I have learned some programming languages such as Pascal, C, C++, Java and PHP. I think C is simple but C++ is too complex. Now I'm interested in web development. So I'm learing PHP and Jave EE. Maybe PHP is my favorite. I had developed a software using PHP -- an online judge, which can be used for programming contest. I think I can provide some help to those who is learning PHP.

Postscript: I like the avatar of Jordan, the administrator. It's really lovely.

Saturday, April 26, 2008

Using '<' Operator to Compare

In C++ Standard Template Library (STL), some algorithms such as sorting, need to compare two elements. STL uses less operator '<' to accomplish the purpose. When you need to apply those algorithms to your custom data structure, you must overload less operator '<'. But sometimes, you need '!=', '>', etc. How to use '<' to implement all the operators?

For example, if you have a<b, then:
  • if you need a>b, just write 'b<a';
  • if you need a!=b, use 'a<b||b<a';
  • if you need a==b, use '!(a<b||b<a)';
  • if you need a>=b, use '!(a<b)';
  • the last, if you need a<=b, use '!(b<a)'.
So, all comparison operators can be implemented by less operator '<'.