Use PHP5 for Layer-3 development

Source: Internet
Author: User
Tags php template
Original article: www.onlamp.compubaphp20041209three_tier.html Three-TierDevelopmentwithPHP5byLuisYordanoCruz12092004 this article demonstrates the powerful function of PHP three-layer development, PEAR: DB_DataObject for business logic, Smarty for display logic, here assuming you are familiar with HTML, Smarty, PEAR :: D original: http://www.onlamp.com/pub/a/php/2004/12/09/three_tier.html
Three-Tier Development with PHP 5
By Luis Yordano Cruz
12/09/2004

This article demonstrates the powerful functions of PHP layer-3 development. PEAR: DB_DataObject is used for business logic, and Smarty is used for display logic.

I have learned about HTML, Smarty, PEAR: DB_DataObject, Mysql, and PHP5. if you need additional knowledge, the following articles explain some principles:

Simplify business logic with PHP DataObject
Smarty introduction: a PHP template engine
PHP scalability: Myth

You should have installed and configured Apache, MySQL, and PHP5 (or IIS, MySQL5, and PHP)

PEAR: DB_DataObject
PEAR: DB_DataObject is an abstract API for user database access. it is an SQL builder and data modeling layer based on PEAR: DB. it

Map database tables to PHP classes and provide public SQL functions such as SELECT, INSERT, UPDATE, and DELETE.

The SQL solution developer can also write good database access code, and encourage the demonstration logic and business logic to have a clear separation.

(The PEAR that DB_OO has been moved to is now DB_DataObject. if you have old code to be updated, view the updates from old db_oo code

DB_DataObjects comments ).

Reading

Upgrading to PHP 5
By Adam Trachtenberg

Table of Contents
Index
Sample Chapter

Read Online -- Safari Search this book on Safari:

Only This Book All of Safari
Code Fragments only
DataObject performs two tasks. First, it builds SQL statements based on the object's variables and the builder

Methods. Second, it acts as a datastore for a table row. There's a core class, which you extend for each

Your tables so that you put the data logic inside the data classes. There's also an unsupported Ded Generator to make

Your configuration files and your base classes.

DataObject executes two tasks. First, it constructs SQL statements and builder methods based on object variables. Second, it is used as the data storage of database tables.

Store. here there is a core class that inherits from each table so that you can put the data logic into the data Class. This also includes a generator,


DataObject greatly simplifies database access code, making it easier to develop large, data-driven sites.

At present, Alan Knowles, the lead developer of PEAR: DB_DataObject, is working on a new project called DBDO,

A C implementation of the PEAR package DB_DataObjects, based on libgda. His goal is to create the next

Generation of PEAR: DB_DataObjects.

SMARTY

Smarty is a PHP template engine that separates content from a web page demonstration. it uses GPL license.

Large projects commonly separate the role of the graphic designer from that of the programmer. However,

Programming in PHP has the tendency to combine those two roles in a person and inside the code. This can bring

Difficulties when it comes time to change some part of the page's design. If the page mixes content and

Presentation, the developer has to crawl through the program to find the presentation. Smarty helps to solve

This problem.

Combining the Two
The first thing to do when starting this project is to create a workspace in which to store the project's code.

Then it's time to configure PEAR: DB_DataObject to connect to the MySQL database MySQL (name: example ),

Map the database tables to PHP classes, and then configure Smarty for the presentation tier for the user. Here

Are those steps in more detail:


Create a work environment

Create a directory named dataobjects.

Install PEAR: DB_DataObject from the command line, and type:
> Pear install Date
> Pear install DB_DataObject
> Pear list

Installed packages:
==============================
PACKAGE VERSION STATE
Archive_Tar 1.2 stable
Console_Getopt 1.2 stable.
DB 1.6.5 stable
DB_DataObject 1.7.1 stable * (Goal)
Date 1.4.3 stable
Mail 1.1.3 stable
Net_SMTP 1.2.6 stable
Net_Socket 1.0.2 stable
PEAR 1.3.1 stable
PHPUnit 1.0.1 stable
XML_Parser 1.2.0 stable
XML_RPC 1.1.0 stable


Install and configure Smarty


Starting from the download, (I used version 2.6.5 of Smarty) decompress it to your own directory. from its libs Directory, put Smarty. class. php,

Copy the Smarty_Compiler.class.php, Config_File.class.php, and debug. tpl files to the dataobjects directory.


You also need to copy the core and plugins directories and all the contents. create several new directories named templates, templates_c, configs,

And cache.


Finally, the dataobjects directory contains:


| ---- Cache
| ---- Configs
| ---- Core
| ---- Plugins
| ---- Templates
| ---- Templates_c

11/10/2004 11: 17 a.m.

.
11/10/2004 11: 17 a.m. ..
11/10/2004 11: 17 a.m. Cache
11/10/2004 11: 17 a.m. Configs
11/10/2004 11: 17 a.m. Core
11/10/2004 11: 17 a.m. Plugins
11/10/2004 11: 17 a.m. Templates
11/10/2004 11: 17 a.m. Templates_c
07/09/2004 a.m. 13,105 Config_File.class.php
16/04/2004 a.m. 5,117 debug. tpl
10/09/2004 p.m. 65,350 Smarty. class. php
10/09/2004 p.m. 90,924 Smarty_Compiler.class.php
4 archivos 174,496 bytes
8 dirs 6,699,454,464 bytes libres


Create a database
Create a database named example, which contains a table named User. you don't have to worry about the mode. we will create it later.


Configure PEAR: DB_DataObject
To build a data object, create the following file

ConfigDB. php
Require_once 'DB/DataObject. php ';
$ Config = parse_ini_file ('example. ini ', TRUE );

Foreach ($ config as $ class =>$ values ){
$ Options = & PEAR: getStaticProperty ($ class, 'options ');
$ Options = $ values;
}
?>

This script creates a connection to the database based on the values in the example configuration file, as shown below.

Example. ini
[DB_DataObject]
Database = mysql: // root: @ localhost/example
Schema_location =/dataobjects/schema/
Class_location =/dataobjects/
Require_prefix =/dataobjects/
Class_prefix = DataObjects _
Extends_location = DB/DataObject. php
Extends = DB_DataObject


Automatic database creation

It contains two processes: creating database object-relationship ing, and automatically creating a class from the user table of the example database. all fields in the table

Will become a class member variable.


Create an appropriate mode:

C: \ PHP \ PEAR \ DB \ DataObject> C: \ PHP \ php.exe createTables. php \
C: \ dataobjects \ example. ini


This will generate the User. php file:

/**
* Table Definition for user
* Www.knowsky.com
*/
Require_once 'DB/DataObject. php ';

Class DataObjects_User extends DB_DataObject
{
### START_AUTOCODE

/* The code below is auto generated do not remove the above tag */
Var $ __table = 'user'; // table name
Var $ user_Id; // int (11) not_null primary_key auto_increment
Var $ first_Name; // string (30) not_null
Var $ last_Name; // string (40) not_null
Var $ email; // string (100) not_null

/* Static get */
Function staticGet ($ k, $ v = NULL ){
Return DB_DataObject: staticGet ('dataobjects _ user', $ k, $ v );
}

/* The code above is auto generated do not remove the tag below */
### END_AUTOCODE
}
?>

It also generates the example. ini configuration file for the user table mode:

[User]
User_Id = 129
First_Name = 130
Last_Name = 130
Email = 130

[User _ keys]
User_Id = N


Smarty files
It's time to create several files for Smarty:

Smarty file
It is time to create several Smarty files:

Include. php
1 2 require ('smarty. class. php ');
3 $ smarty = new Smarty;
4 $ smarty-> template_dir = 'Templates /';
5 $ smarty-> compile_dir = 'Templates _ c /';
6 $ smarty-> config_dir = 'configs /';
7 $ smarty-> cache_dir = 'cache /';
?>

This script instantiate a new Smarty object. set the Smarty attribute.

Index. php
1 2 require ("include. php ");
3 $ smarty-> assign ('title', 'Access MySQL database in three tiers with php ');
4 $ smarty-> assign ('header', 'What wish do? ');
5 $ smarty-> display ('index. tpl ');
?>

Allocate variables to the Smarty template.

Insert. php
1 2 require ("include. php ");
3 $ smarty-> assign ('title', 'Insert data ');
4 $ smarty-> assign ('header', 'Insert data ');
5 $ smarty-> assign ('data1', 'first name ');
6 $ smarty-> assign ('data2 ', 'last name ');
7 $ smarty-> assign ('date3', 'Email ');
8 $ smarty-> display ('Insert. tpl ');
?>

Add the variable to be used in insert. tpl. call the template insert. tpl.

Save. php
1 2 require_once ('Db/DataObject. php ');
3 require ('configdb. php ');
4 $ user = DB_DataObject: factory ('user ');
5 $ user-> first_Name = $ x;
6 $ user-> last_Name = $ y;
7 $ user-> email = $ z;
8 $ user_Id = $ user-> insert ();
9 $ user-> update ();
10 echo "script location. href = 'index. php' script";
11?>

This script saves data by using a PEAR: DataObject for the user table. Line 2 loads the class DataObject, and

Line 3 callconfigdb. php to connect to the database. Line 4 creates an instance of a user object (see User. php ).

Lines 5 through 7 pass the variables collected from the form in insert. tpl ($ x, $ y, and $ z) in order to save

Data in the database. The primary key of the table is an autoincrement column, so it doesn' t need a value there.

Line 8 inserts the object, and line 9 carries out an update.

View. php
1 2 require_once ('Db/DataObject. php ');
3 require ('configdb. php ');
4 require ("include. php ");
5 $ user = DB_DataObject: factory ('user ');
6 $ user-> find ();
7 while ($ user-> fetch ()){
8 $ smarty-> append ('users', array (
'Id' => $ user-> user_Id,
'Firstname' => $ user-> first_Name,
'Lastname' => $ user-> last_Name,
'Email '=> $ user-> EMAIL,
));
}
9 $ smarty-> assign ('title', 'list users ');
10 $ smarty-> assign ('header', 'list user ');
11 $ smarty-> assign ('data0', 'User _ id ');
12 $ smarty-> assign ('data1', 'first name ');
13 $ smarty-> assign ('data2 ', 'last name ');
14 $ smarty-> assign ('date3', 'Email ');
15 $ smarty-> display ('View. tpl ');
16?>

This script displays all the data stored in the user table. it loads the PEAR: DataObject and include. php files (assign variables to the smarty template ).
Row 5th creates a factory for the user object. row 6th executes the find () method. SELECT * FROM user to retrieve data FROM the database.

The fetch () method saves data for the template and returns a record at a time.

Rows 9 to 14 assign other variables to Smarty.


These files should be stored in the dataobjects directory.


For the template, index. tpl, list. tpl, and save. tpl. their code is as follows:

Index. tpl
1
2
3{$ TITLE}
4
5
6





7 8 11 12

9{$ HEADER}
10

13






14 16 19 20 21 24 25

17Onclick = "javascript: location. href = 'Insert. php';">
18

22Onclick = "javascript: location. href = 'View. php';">
23

26
27


On the site homepage, $ TITLE and $ HEADER are displayed on the 3 and 9th rows respectively. these variable values are transmitted from index. php.


This script generates two buttons on the web browser, Insert and View, and they have the corresponding behavior. if you click Insert, the system will call

Use Insert. php. if you click View, view. php will be called.

Insert. tpl
1
2
3{$ TITLE}
4
5
6
7
40
41


This template has a form and two buttons, Add and Return/Cancel.


User input data, first name, last name, and email field. insert. php expect to receive this information in the variable named x, y, z.

Click the Add button to run save. php. if you click Return/Cancel, index. php will be executed.

View. tpl
1
2
3{$ TITLE}
4
5
6





7 8 11 12

9{$ HEADER}
10

13
















14 16 19 22 25 28 29 {section name = display loop = $ users}30 31 34 37 40 43 44 {/section}4546

17{$ Data0}
18

20{$ Data1}
21

23{$ Data2}
24

26{$ Data3}
27

32 {$ users [display]. ID}
33

35 {$ users [display]. FIRSTNAME}
36

38 {$ users [display]. LASTNAME}
39

41 {$ users [display]. EMAIL}
42

47

48



49 50 53 54

51Onclick = "javascript: location. href = 'index. php';">
52

55
56

This template displays all the data stored in the example database.


Finally, the Return button brings the user back to the home page.

All these (*. tpl) files must be stored in the templates directory.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.