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.
Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts
Friday, May 30, 2008
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:
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.
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
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.
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:
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:
$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.
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:
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:
$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.
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?
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?
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:
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" 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.
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.
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:
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.
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.
Subscribe to:
Posts (Atom)