Home > Backend Development > PHP Tutorial > thinksns core architecture and directory structure_PHP tutorial

thinksns core architecture and directory structure_PHP tutorial

WBOY
Release: 2016-07-15 13:21:37
Original
925 people have browsed it

The core and services, public models, plug-ins, widgets, and third-party libraries together form the foundation of the system, on which all other applications are built.

Explanation of terms
Core: Derived from the ThinkPHP framework, it provides the system with core functions such as MVC separation and underlying database support, and provides many convenient class libraries and function libraries for use by other parts of the system. Located in the /core/ directory.
Service: A set of global class libraries that encapsulate specific functions. Located in the /addons/services/ directory, such as email sending (Mail), user authentication (Passport), etc.
Public Model: a set of global general models. Located in the /addons/models/ directory, such as attachment model (AttachModel), area model (AreaModel), etc.
Plug-in: a program file added to achieve a certain function. Located in the /addons/plugins/ directory, it includes third-party platform login plug-ins and medals.
Widget: A set of code blocks that can be called on any HTML page. Located in the /addons/widgets/ directory, including Comment, SelectFriend, etc.
Third-party libraries: other open source third-party libraries. Located in the /addons/libs/ directory, such as phpmailer, etc.
Application: an independent module that implements specific functions, built based on the above system structure. Located in the /apps/ directory, such as Blog, Photo, etc.
API: Application Programming Interface. Located in the /api/ directory, such as Weibo API, user profile API, etc.
-------------------------------------------------- -------------------------------------------------- ----------------------------------------
Weibo
Although Weibo also appears as an independent application of the system (as shown in Figure 1), it also shoulders the responsibility of the core application of the system. Many system elements are completely built on the Weibo application. For example, the Weibo Widget (i.e., the "sharing" function) directly operates Weibo, while the WAP application completely uses the Weibo API architecture.
Roaming Platform
Another special case of system applications is roaming applications. The roaming application comes from Kangsheng's roaming platform. Since the URL of the roaming platform is generated according to the directory structure of UCHome, which is completely different from the directory structure of ThinkSNS, and the portability of the roaming platform needs to be taken into account, so the integrated roaming application does not The standard ThinkSNS2.0 core uses a minimalist version of the framework implemented within the roaming application.
If you are a template developer, you have to pay special attention! Because after you modify the header and left side of the page in the public directory, you also need to modify the header and left side of the page under roaming
(located in /apps/myop/themes/classic/ directory).
-------------------------------------------------- -------------------------------------------------- ----------------------------------------
Directory structure
ThinkSNS2.0
├─ _runtime ------------- Runtime cache
├─ addons ------------- extension library
│ ├─ libs ------------- Third-party libraries
│ ├─ models ------------- Public Model
│ ├─ plugins ------------- Plugins
│ │ ├─ login ------------- Third-party platform login plug-in
│ │ ├─ Medal ------------- Medal
│ │ └─ Tags ------------- Tags
│ ├─ services ------------- System services
│ └─ widgets ------------- System Widget
├─ api ------------- API library
├─ apps ------------- System applications
│ ├─ admin ------------- Management background
│ ├─ home ------------- Home app
│ ├─ myop ------------- roaming application
│ ├─ wap ------------- Mobile WAP
│ └─ weibo ------------- Weibo application
├─ core ------------- core
│ ├─ sociax ------------- System core files
│ ├─ ThinkPHP ------------- ThinkPHP core
│ └─ sociax.php ------------- Core boot file
├─ data ------------- Site data
├─ install ------------- System installation file
├─ public
│ ├─ admin ------------- Management background style
│ ├─ js ------------- System JS library
│ └─ themes ------------- System templates
├─ access.php ------------- Node permission control file
├─ cleancache.php ------------- cache cleaning file
├─ config.inc.php ------------- Site configuration file
├─ index.php ------------- Site entry file
├─ shorturl.php ------------- Short address file
└─ thumb.php ------------- Automatic thumbnail generation file
-------------------------------------------------- -------------------------------------------------- --------------------------
Application architecture and directory structure
Directory location and structure of the application:
ThinkSNS2.0
├─ apps
├─ app
├─ Appinfo ------------- Installation information, installation and uninstallation execution files, icons
├─ Common ------------- Function library common.php
├─ Conf ------------- Project configuration config.php
├─ Language ------------- Notifications, dynamic language packs
├─ Lib
│ ├─ Action ------------- Operation class library
│ ├─ Model ------------- Model class library
│ └─Widget ------------- Plug-in library
└─ Tpl ------------- Template, css, js files
Entry file
ThinkSNS2.0 has only one public entry file, which is index.php in the ThinkSNS directory.
URL Pattern
The access method of the URL is index.php?app=APP_NAME&mod=Action&act=function
Function library
The application's own function library can be placed in Common/common.php in the application directory. The functions here will be loaded together with the application and can be called at will within the application. For the system function library, please refer to "Function Library" in the appendix.
Template
[…]
10/32
The style files of the application are uniformly stored in the Public/ directory under Tpl, and are referenced through ../Public/xxx.css. The JS files of the application are uniformly placed in the Public/js/ directory under Tpl/ under the application project. Referenced via ../Public/js/xxx.js.
-------------------------------------------------- -------------------------------------------------- ------------------
Development Guide
3.1 Naming and coding standards
Refer to ThinkPHP’s naming and coding specifications: http://thinkphp.cn/Manual/20
3.2 Using function libraries, class libraries and Widgets
Use system function library
System functions are located in the /core/sociax/functions.php and /core/sociax/extend.php files. They are globally valid functions and can be called directly.
How to get user nickname: $uname = getUserName($uid);
Using the Service
The service is located in the /addons/services/ directory. Use service('serviceName')->method ($param); to use the service.
For example, how to verify whether the user is logged in: $is_logged = service('Passport')->isLogged();
Use public Model
The public Model is located in the /addons/models/ directory. Use the public Model through model('modelName')->method ($param);.
How to get the area list: $area_list = model('Area')->getAreaList();
Use Widget
Widget is located in the /addons/widgets/ directory and is called via W('widgetName',array('param'=> 'value')). Generally, Widgets are used in pages, so the calling method is: {:W('widgetName',
11/32
array('param'=>'value'))}.
How to display people you may know on the page: {:W('RelatedUse',array('uid'=>'1'))}
Use third-party libraries
Third-party libraries are generally placed in the /addons/libs/ directory. You can introduce the files through include_once and other functions before use.
3.3 Use pop-up windows, prompt messages, and editors
In the world of ThinkSNS2.0, the jQuery library is our default JS framework, which is automatically loaded at the head of the page. ThinkSNS2.0 encapsulates pop-up windows, prompt messages and KISSY editor based on jQuery. This section mainly introduces how to use them (jQuery library official document: http://docs.jquery.com/Main_Page).
Pop-up window
Figure 2 Pop-up window rendering
As shown in Figure 2, the pop-up window contains at least three parts: title, close button and content. To ensure the continuity of user operations, "OK" and "Cancel" buttons are generally added to the content part.
 Pop-up window calling method:
<script></div> <div>function yourFunc() {</div> <div>ui.box.load(your_url, {title:'Here is the title'});</div> <div>}</div> <div></script>
 Place the content of the pop-up window in your_url. NOTE: The OK and Cancel buttons are also part of the content!
 Close the pop-up window:
<script></div> <div>function close() {</div> <div>ui.box.close();</div> <div>}</div> <div></script>
12/32
Prompt message
Figure 3 Prompt message rendering
Calling method:
<script></div> <div>function success() {</div> <div>ui.success("Update completed");</div> <div>}</div> <div>function error() {</div> <div>ui.error("New Email already exists");</div> <div>}</div> <div></script>
Editor
The editing-related JS is automatically loaded at the head of the page. You only need to call E = KISSY.Editor("idOfTextarea"); to complete the loading of the editor. Such as:
<script></div> <div>$(document).ready(function(){</div> <div>E = KISSY.Editor("idOfTextarea");</div> <div>});</div> <div></script>
3.4 ThinkPHP Development Guide
ThinkPHP official documentation – Development Guide: http://thinkphp.cn/Manual/50
ThinkPHP official documentation – template guide: http://thinkphp.cn/Manual/194
3.5 Application Development
After reading the previous introduction and explanation, I believe everyone is ready to take action. This chapter takes the development of a gift application as an example to show you the entire process of developing an application. If you are a ThinkPHP development expert, you will find that developing an application is actually creating a new project. This is also the charm of ThinkSNS2.0: application independence.
13/32
Development Process
General process of ThinkSNS2.0 application development:
1. Create database and data tables (no database operations can be skipped)
2. Name the project and create the project directory
3. Create controller class
4. Create model class
5. Create template file
6. Run and debug
Development requirements and development goals
Our gift application needs to implement the following functions:
1. Users can send gifts to people they follow or fans
2. Users can see all the gifts they have given out
3. Users can see all the gifts given to them by others
4. Users can give gifts back to friends
5. Users can send notification messages at the same time when sending gifts
6. After successfully sending the gift, the user can send a Weibo sharing message
7. Administrators can add, modify, and delete gifts and gift types in the backend
8. The administrator can configure the points consumption type of the gift in the background: Points? experience?
9. Implement a complete point consumption function. If the user has insufficient points, the gift cannot be given
Create data table
According to the above demand analysis, we need to design three data tables, one to save the classification information of gifts, another to save the gift information, and another to save the gift-giving records between users. When adding a data table, please pay attention to the naming format of the table: database table prefix + table name, where the database table prefix has been defined in the DB_PREFIX constant in config.inc.php.
Added gift classification list:
Field
Type
Description
id
int
name
varchar
Category name
status
tinyint
Whether to enable 0 disable 1 enable (default)
cTime
int
Creation time
Added two default categories: popular gifts and latest arrivals
Add gift information table:
Field
Type
Description
id
int
categoryId
int
Category ID, corresponding to the ID of the above classification table
name
varchar
Gift name
num
int
Inventory
14/32
price
int
Price
img
varchar
Gift pictures
status
tinyint
Whether to enable 0, disable 1, enable (default)
cTime
int
Creation time
Here, of course, we also need to prepare part of the gift in advance, that is, the initialized gift information.
Added gift record list:
Field
Type
Description
id
int
fromUserId
int
Gift giver ID
toUserId
int
Gift recipients
giftPrice
int
Price
giftImg
varchar
Gift pictures
sendInfo
text
Additional information
sendWay
tinyint
How to give: 1 Public 2 Private 3 Anonymous
cTime
int
Creation time
At this point, the data table design is completed.
The install.sql file in the /gift/Appinfo/ folder in the application directory contains the above SQL statements for creating tables and inserting predefined data.
Create application directory
Figure 4 Application directory structure
As shown in the picture above, we first add the gift directory gift in the /apps/ directory, and then create the directory shown in the picture above in the /apps/gift/ directory (please pay attention to the capitalization).
 App directory Lib:
The files of Action controller and Model are stored in the application directory.
 App template directory Tpl:
Since this gift application only has one set of templates, we directly create the default template directory default/ in the Tpl/ directory, and then add the Index template we need and a public template directory Public/ in the default/ directory.
 Public function directory Common:
The public functions of this application can be stored here. The file name is common.php. This file will be automatically loaded during execution. These functions can be used directly in the files in the Action/ and Model/ directories without the need to introduce the file again. . At the same time, we can also directly use the public functions in ThinkSNS2.0. These functions are saved in
15/32
functions.php and extend.php under the /core/sociax/ folder, which include our most commonly used data processing or data acquisition, such as h(), t() filter functions, getUserName() function (in The calling methods of the template file are: {$userId|getUserName}), getUserFace() function and friendlyDate() function (the usage is the same as getUserName()). The above functions are recommended for everyone to use.
 App configuration directory Conf:
If the application needs to modify the system default constants or add some configuration parameters required by the project, you need to create a configuration file named config.php under the Conf/ directory of the project, and the file will automatically load. The public function directory and application configuration directory are non-essential directories. Whether they are needed depends on the application development decision. Only the public function folder is used in this gift development.
● Language directory Language:
Used to save the application’s system notification templates and dynamic templates. The system notification template will be used in this gift development. Create the Chinese language pack directory cn/ in the Language/ directory, and then add the notification template file notify.php (dynamic is the same, but the file name is: feed.php).
● Installation package directory Appinfo:
Used for application installation/uninstallation operations in the ThinkSNS background, it must contain the info.php file (used to obtain application information). If it contains the install.php or uninstall.php file, it will be automatically called when the application is installed or uninstalled. .
Start programming
 Public function layer
In the Common/ directory, create a new common.php file (note the case of the file name) and write the required functions, such as the function to obtain application configuration parameters:
function getConfig($key=NULL){
[…]
}
Please refer to this file for detailed code.
The functions in this file can be used directly in files in the Action/, Model/ and Tpl/ directories.
= MODEL layer
In the Lib/Model/ directory, create three new files: GiftCategoryModel.class.php, GiftModel.class.php and UserGiftModel.class.php. The respective codes are as follows:
class GiftCategoryModel extends Model{ }
class GiftModel extends Model{ }
class UserGiftModel extends Model{ }
Through the above steps, we have now established an association between the database table and the model class. In the project's Action class and Model class, you can directly perform related operations on the database.
Some people are used to encapsulating some methods in the Model class, which is more in line with the MVC specification, and some people are used to writing all methods in the Action to facilitate the reading of the program. This mainly depends on personal habits. In this development, the basic methods are written into the Model layer. Please refer to the corresponding file for detailed codes.
=ACTION layer
In the Lib/Action/ directory, create IndexAction.class.php and create the code as follows:
class IndexAction extends Action{ }
Detailed code is included in this file.
 Template layer
16/32
We need two folders in the Tpl/default/ directory: Index and Public. The Index folder name corresponds to the IndexAction.class.php file, which means that the files under the Index folder are all templates required by the IndexAction.class.php file. We generally place the public files of the application in the Tpl/default/Public/ directory, such as the gift images, JS files, CSS files, application header file _mainNav.html, etc. of the gift application. Of course, the setting of these directories is entirely up to the developer, as long as the path to the calling file is correct.
Let’s first take a look at the general structure of the ThinkSNS2.0 template file. After developers introduce the application’s own style files and JS files, they can directly add the corresponding display code to the canvas layer:
[…]
Please refer to the specific code for details. The following introduces several codes in the template file that are valuable for learning.
1. ThinkSNS2.0 fully uses jQuery technology. jQuery is a good lightweight JS framework that can help us quickly develop JS applications and change our habit of writing JavaScript code to a certain extent. ThinkSNS2.0 has already introduced the jQuery library in the header file, so developers do not need to introduce it again.
2. The index.html file in the Tpl/default/Index/ directory. This is the template of the gift center. The function of selecting friends to send uses the friend selection widget. You only need to add {:W("SelectFriend to the template. ")}, then use $_POST['fri_ids'] to get the selected friend ID.
3. Because we use findPage() to obtain the list of gifts received and sent, the returned data already has paging variables. Just add the following code to the appropriate place in the template:
17/32
Added points consumption function
The above program has basically completed all operations on gifts. Next, we need to add the point consumption function. As for the type of points used for gift consumption, whether it is points or experience, it can be set in the background. Please see the background program instructions for details. First, add the function of displaying how many points the current user has on the gift sending page. We only need to add the following program to the index() method of the IndexAction.class.php file:
//Get the current user’s points
$money = X('Credit')->getUserCredit($this->mid);
$moneyType = getConfig('credit');
$this->assign('money',$money[$moneyType]);
Add the following line of code to the template for sending gifts:
The {$money.alias} I currently have are: {$money.credit}
Then in the function of sending gifts (sendGift() method of UserGiftModel.class.php), add the corresponding point deduction program for the selected gift:
//Deduct corresponding points
$giftPrice = intval($giftInfo['price']);
$prices = $userNum*$giftPrice;
$moneyType = getConfig('credit');
//Point operation
$setCredit = X('Credit');
//Check whether the points are enough
$userCredit = $setCredit->getUserCredit($fromUid);
if($userCredit[$moneyType]['credit']<$prices){
return $userCredit[$moneyType]['alias'].'Insufficient, gift failed~';
}
$setCredit->setUserCredit($fromUid,array($moneyType=>$prices),-1);
The points operation class in the public class library services is called here, that is, X('Credit').
The points consumption function has been added here.
Add notification function
First you need to add a gift notification template. Create a folder cn in the Language/ directory, and then create a notification template file notify.php in the cn folder. The code is as follows:
return array(
'gift_send' => array(
'title' => '{actor} gave you a gift',
'body' => $img.'
'.$sendback.'

'.$content.'


Go and have a look
18/32
',
),
);
?>
Add the following program after successfully sending the gift:
//Send notification to the recipient
$this->__doNotify($toUser,$sendInfo,$giftInfo,$fromUid,$appId);
For the implementation of the __doNotify() method, please refer to the specific code.
The system notification class in the public class library services is called here, that is, X('Notify').
The notification function is completed here.
Added dynamic sending function
The mechanism for sending updates is exactly the same as the mechanism for sending notifications. The only difference is the following two points:
 Notification uses /Language/cn/feed.php, while dynamic use /Language/cn/notify.php
 Notification service uses X('Notify') or service('Notify'), while dynamic use X('Feed') or service('Feed')
Since the gift application does not use dynamics, I will not go into details here.
Added Weibo sharing function
First we need to add a gift template in "Admin Backend - Content - Template Management":
19/32
Before assembling the notification data, initialize a gift object variable:
//The name of the gift object is used for public Weibo gifting
$toUserName = NULL;
Add the following code in the notification message of the public gift to @ reach each recipient:
//Gift object name
$toUserName .= '@'.getUserName($fid).' ';
After the notification information is assembled, add the following code to temporarily store the Weibo information in SESSION:
// If public, please send me a small amount
if($toUserName){
$_SESSION['gift_send_weibo'] = urlencode ( serialize ( array(
'user' => $toUserName,
'title' => $giftInfo['name'],
'content' => $data['content'],
'url' => U('gift/Index/index', array(
'uid' =>$fid,
'type' =>1,
'type_data'=>realityImageURL($giftInfo['img']))),
)));
}
Add the following code in the sendbox() function in the Lib/Index/ IndexAction.class.php file:
//Determine whether there is public gift information. If it exists, assign it to the template for sending Weibo if(isset($_SESSION['gift_send_weibo'])&&!empty($_SESSION['gift_send_weibo'])){
$this->assign('tpl_data',$_SESSION['gift_send_weibo']);
unset($_SESSION['gift_send_weibo']);
}
In the gift sendbox.html template file under the Tpl/default/Index/ directory, add a WeiboWidget reference (loaded only when the Weibo information sent exists), as follows:
{:W('Weibo',array(
'tpl_name'=>'gift_send_weibo',
'button_title'=>'Share',
))}
<script>_widget_weibo_start('', '{$tpl_data}');</script>
The function of public giving and posting on Weibo is now complete.
Add application background
ThinkSNS2.0 adds a management background to an application very simply. Just add the AdminAction.class.php file directly in the Action/directory of the application, then import and inherit the AdministratorAction class to complete permission management:
20/32
//Introducing background management class
import('admin.Action.AdministratorAction');
class AdminAction extends AdministratorAction {
function _initialize(){
// Management permission determination
parent::_initialize();
[…]
}
[…]
}
?>
Note: In the _initialize function, parent::_initialize() must first be executed to determine management permissions.
For more detailed codes, please see the specific documents.
Then we add the corresponding management page template, add the Admin/ directory under the Tpl/default/ directory, and then add _header.html, _footer.html, _tab.html, index.html, giftlist.html in this directory , category.html, edit_gift_tab.html, edit_category_tab.html several template files. The template development method is the same as the front-end template and will not be repeated here.
Create installation/uninstallation package
Add an installation information directory under the application directory, name it Appinfo, and then add application icons (ico_app.gif, ico_app_large.gif), application configuration files (info.php), and application installation files (install. php), application database file (install.sql) and application uninstall file (uninstall.php).
 Configuration file content:
if (!defined('SITE_PATH')) exit();
return array(
//Application name [required]
'NAME' => 'Gift',
// Application introduction [required]
'DESCRIPTION' => 'Gift giving',
// Hosting type [required] (0: local application, 1: remote application)
'HOST_TYPE' => '0',
// Front desk entrance [required] (Format: Action/act)
'APP_ENTRY' => 'Index/index',
// Application icon [required]
'ICON_URL' => SITE_URL . '/apps/gift/Appinfo/ico_app.gif',
// Application icon [required]
'LARGE_ICON_URL' => SITE_URL . '/apps/gift/Appinfo/ico_app_large.gif',
//Backstage entrance [optional]
'ADMIN_ENTRY' => 'Admin/index',
// Statistics entrance [optional] (Format: Model/method)
21/32
'STATISTICS_ENTRY' => 'GiftStatistics/statistics',
[…]
);
?>
Note: SITE _URL is the site root directory URL. If you use it directly, the program will automatically interpret it as an absolute URL. Another advantage is that this information does not need to be modified when the website is transferred, and the program will automatically interpret it. Assign the new URL to it. Of course, you can also use absolute URLs.
● Installation file content:
The statements for database operations are all placed in the database file install.sql. The function of install.php is to execute this file:
if (!defined('SITE_PATH')) exit();
header('Content-Type: text/html; charset=utf-8');
$sql_file = APPS_PATH.'/gift/Appinfo/install.sql';
//Execute sql file
$res = M('')->executeSqlFile($sql_file);
if(!empty($res)){//Error
echo $res['error_code'];
echo '
';
echo $res['error_sql'];
//Clear imported data
include_once(APPS_PATH.'/gift/Appinfo/uninstall.php');
exit;
}
?>
 Database file content:
First, write the add statements for the three data tables of the application; then, add the insert statements for the application system configuration information and the Weibo template. If there is an application that sets the points rules, also add the insert statements for the point rules. , you can refer to the database files of applications such as logs and photo albums. The code is as follows:
SET FOREIGN_KEY_CHECKS=0;
[...the sql statements of three data tables and their preset information]
#Add ts_system_data data
REPLACE INTO `ts_system_data` (`uid`,`list`,`key`,`value`,`mtime`)
VALUES
(0, 'gift', 'credit', 's:5:"score";', '2010-12-24 11:22:17');
#Template data
DELETE FROM `ts_template` WHERE `name` = 'gift_send_weibo';
INSERT INTO `ts_template` (`name`, `alias`, `title`, `body`, `lang`, `type`, `type2`, `is_cache`, `ctime`)
22 / 32
VALUES
('gift_send_weibo', 'gift giving', '','I gave {user} a gift: [{title}] {content} Participate in gift giving {url}', 'zh', 'gift', 'weibo', 0, 1290417734);
The sql files and statements exported by the tool can be used directly here.
 Uninstall file content:
Delete the application’s data table, application system configuration information and Weibo template. If the application also sets points rules, its points rules must also be deleted at the same time. You can refer to the uninstall files of applications such as logs and photo albums.
if (!defined('SITE_PATH')) exit();
$db_prefix = C('DB_PREFIX');
$sql = array(
// gift data
"DROP TABLE IF EXISTS `{$db_prefix}gift`;",
"DROP TABLE IF EXISTS `{$db_prefix}gift_category;",
"DROP TABLE IF EXISTS `{$db_prefix}gift_user;",
// ts_system_data data
"DELETE FROM `{$db_prefix}system_data` WHERE `list` = 'gift'",
// Template data
"DELETE FROM `{$db_prefix}template` WHERE `name` = 'gift_send_weibo';",
);
foreach ($sql as $v)
M('')->execute($v);
?>
At this point, the installation and uninstallation package is completed.
After logging in to the backend, go to "Application->Application Management->Add Application" and click "Install" the application. Then update the system cache and you can see our gift application in the application list in the foreground.
Debugging
There are many ways to debug our programs. Here we recommend several commonly used debugging methods.
● Use the dump() method that comes with ThinkPHP to print out the process variables to see if the results are the same as expected
● Use ThinkPHP’s getLastSql() method to obtain the final SQL statement and print it out with dump() to check whether the SQL statement is correct
● Add the DEBUG_MODE constant in the Conf/config.php file and assign it to true, that is, turn on the debug mode of ThinkPHP (Note: the cache needs to be cleared after modification)

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/477150.htmlTechArticleThe core and services, public models, plug-ins, widgets, and third-party libraries together form the foundation of the system. All applications are built on top of it. Terminology explanation Core: Derived from the ThinkPHP framework,...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template