本文章為原創內容,轉載請注明出處。
上周班上的小范同學問我廣告模塊怎么設計,我說你去參考phpcms啊,他上面的廣告模塊設計的很不錯呢。
那么,就讓我們開始吧。
## PHPCMS廣告模塊詳細分析——廣告的生成
### 一、功能。
我們首先從功能開始,這里用的是最新下載的?**[phpcms_v9.5.2_UTF8](http://www.phpcms.cn/index.php?m=content&c=down&a_k=59feBgIEUgIBVFEDA1UBAQBYBFIBU1EHAgUDC1EIBA0HQkALFFlfAxcCXFtHEUUIFhZRWRQNXwkHUBxIDRFaVUVKUFgdQlsdCEpUHEMNRVFUSmpAWk0GSFRrZ2wjWRdCXxQVUg8ERF9eAARfWgEIAR9aVEIKBw5XXw)**?,有興趣的同學可以下載下來。
跳過安裝步驟,我們進入后臺,直接看廣告模塊。
廣告位列表

廣告列表

廣告統計

那么,我們就很清楚phpcms廣告模塊的功能了。
每個廣告位最多顯示一個廣告,但是可以設置多個廣告進行時間排序的播放,每一個廣告都會有自己的統計信息,統計點擊量和顯示量。
### 二、數據庫分析。
讓我們打開phpcms的數據庫,分析下數據是怎么存儲的。
打開數據庫,我們會發現三個名字中帶有poser的表,沒錯!這(至少)三個表就是負責存儲廣告相關數據的。
廣告位 poster_space

廣告 poster

廣告瀏覽IP統計 poster_201312

這樣的話,數據統計也是很明確的啦!?
poster_space表中存儲著廣告位,poster中存儲每條廣告的信息,包含統計信息的點擊量,poster_201312存放著2013年12月的廣告IP統計,因為每個用戶的IP都不一樣,數據量會非常大,所以要分月存放。
### 三,代碼分析。
上面的內容都是鋪墊,對于程序員們來說,源代碼才是真刀實槍!
上碼!

廣告模塊存放于phpcms\modules\poster ,是作為一個phpcms的模塊的存在。
我們按流程分析,按照 **廣告位->廣告->前臺調用** 這個順序,把源代碼擼一遍!
1.space.php
先貼個幾個圖

廣告模版

~~~
<?php
/**
* 這里是小雨的注釋
*
* 廣告模塊的代碼量其實不大,也就不到300行,除去官方注釋和空行之外也就沒有多少了。
*
*/
defined('IN_PHPCMS') or exit('No permission resources.');
pc_base::load_app_class('admin', 'admin', 0);
pc_base::load_sys_class('form', '', 0);
/**
* 這里是小雨的注釋
*
* 這里繼承了admin類,為的是不允許前臺調用
*
* 寫這個注釋是為了和后面的index.pphp進行區分
*/
class space extends admin {
private $M, $db;
/**
* 這里是小雨的注釋
*
* 構造函數,因為phpcms的多站點管理,所以在構造函數中獲取了當前站點的id并放入M中,方便下面的方法調用。
*/
function __construct() {
parent::__construct();
$setting = new_html_special_chars(getcache('poster', 'commons'));
$this->M = $setting[$this->get_siteid()];
$this->db = pc_base::load_model('poster_space_model');
}
public function init() {
$TYPES = $this->template_type();
$page = max(intval($_GET['page']), 1);
$infos = $this->db->listinfo(array('siteid' => $this->get_siteid()), '`spaceid`', $page);
$pages = $this->db->pages;
$big_menu = array('javascript:window.top.art.dialog({id:\'add\',iframe:\'?m=poster&c=space&a=add\', title:\'' . L('add_space') . '\', width:\'540\', height:\'320\'}, function(){var d = window.top.art.dialog({id:\'add\'}).data.iframe;var form = d.document.getElementById(\'dosubmit\');form.click();return false;}, function(){window.top.art.dialog({id:\'add\'}).close()});void(0);', L('add_space'));
include $this->admin_tpl('space_list');
}
/**
* 添加廣告版塊
*/
public function add() {
if (isset($_POST['dosubmit'])) {
$space = $this->check($_POST['space']);
$space['setting'] = array2string($_POST['setting']);
$space['siteid'] = $this->get_siteid();
$spaceid = $this->db->insert($space, true);
if ($spaceid) {
if ($space['type'] == 'code') {
$path = '{show_ad(' . $space['siteid'] . ', ' . $spaceid . ')}';
} else {
$path = 'poster_js/' . $spaceid . '.js';
}
$this->db->update(array('path' => $path), array('siteid' => $this->get_siteid(), 'spaceid' => $spaceid));
showmessage(L('added_successful'), '?m=poster&c=space', '', 'add');
}
} else {
$TYPES = $this->template_type();
/**
* 這里是小雨的注釋
*
* 沒錯!這里是添加廣告版位的控制器,那么我們在上面的圖中看到的廣告位的下拉菜單來自哪里呢
* 讓我們繼續分析下面的函數 getcache
*/
$poster_template = getcache('poster_template_' . $this->get_siteid(), 'commons');
$show_header = $show_validator = true;
include $this->admin_tpl('space_add');
}
}
/**
* 編輯廣告版位
*/
public function edit() {
$_GET['spaceid'] = intval($_GET['spaceid']);
if (!$_GET['spaceid'])
showmessage(L('illegal_operation'), HTTP_REFERER);
if (isset($_POST['dosubmit'])) {
$space = $this->check($_POST['space']);
$space['setting'] = array2string($_POST['setting']);
/**
* 這里是小雨的注釋
*
* 修改提交的時候,通過判斷表單中的廣告位類型,寫入了不同的值到了路徑這個參數
*/
if ($space['type'] == 'code') {
$space['path'] = '{show_ad(' . $this->get_siteid() . ', ' . $_GET['spaceid'] . ')}';
} else {
$space['path'] = 'poster_js/' . $_GET['spaceid'] . '.js';
}
if (isset($_POST['old_type']) && $_POST['old_type'] != $space['type']) {
$poster_db = pc_base::load_model('poster_model');
$poster_db->delete(array('spaceid' => $_GET['spaceid']));
$space['items'] = 0;
}
if ($this->db->update($space, array('spaceid' => $_GET['spaceid'])))
showmessage(L('edited_successful'), '?m=poster&c=space', '', 'testIframe' . $_GET['spaceid']);
} else {
$info = $this->db->get_one(array('spaceid' => $_GET['spaceid']));
/**
* 這里是小雨的注釋
*
* 修改的時候將存入數據庫的 setting字段轉化為數組
*/
$setting = string2array($info['setting']);
$TYPES = $this->template_type();
/**
* 這里是小雨的注釋
*
* 拿到了廣告模版的緩存,注意,是緩存,也就是存在原始文件,因為在上面的數據庫中并沒有存儲模版的信息
*/
$poster_template = getcache('poster_template_' . $this->get_siteid(), 'commons');
$show_header = $show_validator = true;
include $this->admin_tpl('space_edit');
}
}
/**
* 廣告版位調用代碼
*/
public function public_call() {
$_GET['sid'] = intval($_GET['sid']);
if (!$_GET['sid'])
showmessage(L('illegal_action'), HTTP_REFERER, '', 'call');
$r = $this->db->get_one(array('spaceid' => $_GET['sid'], 'siteid' => $this->get_siteid()));
include $this->admin_tpl('space_call');
}
/**
* 廣告預覽
*/
public function public_preview() {
if (is_numeric($_GET['spaceid'])) {
$_GET['spaceid'] = intval($_GET['spaceid']);
$r = $this->db->get_one(array('spaceid' => $_GET['spaceid'], 'siteid' => $this->get_siteid()));
$scheme = $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
/**
* 這里是小雨的注釋
*
* 在這里,同樣的對 廣告位 類型是 代碼 的進行了特殊待遇
*
*/
if ($r['type'] == 'code') {
$db = pc_base::load_model('poster_model');
$rs = $db->get_one(array('spaceid' => $r['spaceid'], 'siteid' => $this->get_siteid()), 'setting', '`id` ASC');
if ($rs['setting']) {
$d = string2array($rs['setting']);
$data = $d['code'];
}
} else {
$path = APP_PATH . 'caches/' . $r['path'];
}
include $this->admin_tpl('space_preview');
}
}
private function template_type() {
pc_base::load_app_func('global', 'poster');
return get_types();
}
/**
* 刪除廣告版位
* @param intval $sid 廣告版位的ID,當批量刪除時系統會遞歸刪除
*/
public function delete() {
if ((!isset($_GET['spaceid']) || empty($_GET['spaceid'])) && (!isset($_POST['spaceid']) || empty($_POST['spaceid']))) {
showmessage(L('illegal_parameters'), HTTP_REFERER);
} else {
if (is_array($_POST['spaceid'])) {
array_map(array($this, _del), $_POST['spaceid']); //如果是批量操作,則遞歸數組
} elseif ($_GET['spaceid']) {
$_GET['spaceid'] = intval($_GET['spaceid']);
$db = pc_base::load_model('poster_model');
$db->delete(array('siteid' => $this->get_siteid(), 'spaceid' => $_GET['spaceid']));
$this->db->delete(array('siteid' => $this->get_siteid(), 'spaceid' => $_GET['spaceid']));
}
showmessage(L('operation_success'), HTTP_REFERER);
}
}
/**
* 廣告位刪除
* @param intval $spaceid 專題ID
*/
private function _del($spaceid = 0) {
$spaceid = intval($spaceid);
if (!$spaceid)
return false;
$db = pc_base::load_model('poster_model');
$db->delete(array('siteid' => $this->get_siteid(), 'spaceid' => $spaceid));
$this->db->delete(array('siteid' => $this->get_siteid(), 'spaceid' => $spaceid));
return true;
}
/**
* 廣告模塊配置
*/
public function setting() {
if (isset($_POST['dosubmit'])) {
//讀取了緩存
$setting = getcache('poster', 'commons');
$setting[$this->get_siteid()] = $_POST['setting'];
setcache('poster', $setting, 'commons'); //設置緩存
$m_db = pc_base::load_model('module_model'); //調用模塊數據模型
$setting = array2string($_POST['setting']);
$m_db->update(array('setting' => $setting), array('module' => ROUTE_M)); //將配置信息存入數據表中
showmessage(L('setting_updates_successful'), HTTP_REFERER, '', 'setting');
} else {
/**
* 這里是小雨的注釋
*
* 注意這個函數
* extract() 函數從數組中把變量導入到當前的符號表中
* 也就是將構造函數中的,從緩存中取出的設置的數組直接打散作為變量
* @ 的符號是防止報錯的
*/
@extract($this->M);
include $this->admin_tpl('setting');
}
}
/**
* 配置模板
*/
public function poster_template() {
/**
* 這里是小雨的注釋
*
* 這里配置了模版,也就是從文件中讀取
*
*/
$tpl_root = pc_base::load_config('system', 'tpl_root');
$templatedir = PC_PATH . $tpl_root . pc_base::load_config('system', 'tpl_name') . DIRECTORY_SEPARATOR . 'poster' . DIRECTORY_SEPARATOR;
/**
*
* 這里的$templatedir 為 phpcms\templates/default\poster\
*
*/
$poster_template = getcache('poster_template_' . get_siteid(), 'commons');
/**
* 找到所有的html的文件,循環得到不包含擴展名的文件名,作為配置項
*/
$templates = glob($templatedir . '*.html');
if (is_array($templates) && !empty($templates)) {
foreach ($templates as $k => $tem) {
$templates[$k] = basename($tem, ".html");
}
}
$big_menu = array('javascript:window.top.art.dialog({id:\'add\',iframe:\'?m=poster&c=space&a=add\', title:\'' . L('add_space') . '\', width:\'540\', height:\'320\'}, function(){var d = window.top.art.dialog({id:\'add\'}).data.iframe;var form = d.document.getElementById(\'dosubmit\');form.click();return false;}, function(){window.top.art.dialog({id:\'add\'}).close()});void(0);', L('add_space'));
include $this->admin_tpl('poster_template');
}
/**
* 刪除模板配置
*/
public function public_tempate_del() {
if (!isset($_GET['id']))
showmessage(L('illegal_parameters'), HTTP_REFERER);
$siteid = $this->get_siteid();
$poster_template = getcache('poster_template_' . $siteid, 'commons');
/**
*
* 這里在刪除的時候只是修改了緩存文件中的,并沒有修改原來的哦
*
*/
if ($poster_template[$_GET['id']]) {
unset($poster_template[$_GET['id']]);
}
setcache('poster_template_' . $siteid, $poster_template, 'commons');
showmessage(L('operation_success'), HTTP_REFERER);
}
/**
* 配置模板
*
* 注:這里只能對 'iscore' => 0, 的模版進行設置哦
*/
public function public_tempate_setting() {
$siteid = $this->get_siteid();
$poster_template = getcache('poster_template_' . $siteid, 'commons');
if (isset($_POST['dosubmit'])) {
if (is_array($_POST['info']['type']) && !empty($_POST['info']['type'])) {
$type2name = array('images' => L('photo'), 'flash' => L('flash'), 'text' => L('title'));
$type = array();
foreach ($_POST['info']['type'] as $t) {
if (in_array($t, array('images', 'flash', 'text'))) {
$type[$t] = $type2name[$t];
} else {
continue;
}
}
}
unset($_POST['info']['type']);
$_POST['info']['type'] = $type;
$poster_template[$_POST['template']] = $_POST['info'];
/**
*
* 這里設置了模版的緩存,放在了
* caches/caches_commons/caches_data/poster_template_1.cache
* 中,特佩服phpcms的緩存
*/
setcache('poster_template_' . $siteid, $poster_template, 'commons');
showmessage(L('setting_success'), '', '', 'testIframe');
} else {
if (!isset($_GET['template'])) {
showmessage(L('illegal_parameters'));
} else {
$template = $_GET['template'];
}
if ($poster_template[$template]) {
$info = $poster_template[$template];
if (is_array($info['type']) && !empty($info['type'])) {
$type = array();
$type = array_keys($info['type']);
unset($info['type']);
$info['type'] = $type;
}
}
include $this->admin_tpl('template_setting');
}
}
/**
* 更新js
*/
public function create_js($page = 0) {
$page = max(intval($_GET['page']), 1);
if ($page == 1) {
/**
* 這里是小雨的注釋
*
* 獲取了當前站點下能用的廣告做了數量的分頁
*
*
*/
$result = $this->db->get_one(array('disabled' => 0, 'siteid' => get_siteid()), 'COUNT(*) AS num');
if ($result['num']) {
$total = $result['num'];
$pages = ceil($total / 20);
}
} else {
$pages = $_GET['pages'] ? intval($_GET['pages']) : 0;
}
$offset = ($page - 1) * 20;
$data = $this->db->listinfo(array('disabled' => 0, 'siteid' => get_siteid()), 'spaceid ASC', $page);
/**
*
* 其實這個方法只是個套子,真正的更新js在下面
*
* 讀取了html的類
* 使用了html中的create_js,來更新了js
*/
$html = pc_base::load_app_class('html');
foreach ($data as $d) {
if ($d['type'] != 'code') {
$html->create_js($d['spaceid']);
} else {
continue;
}
}
$page++;
if ($page > $pages) {
showmessage(L('update_js_success'), '?m=poster&c=space&a=init');
} else {
showmessage(L('update_js') . '<font style="color:red">' . ($page - 1) . '/' . $pages . '</font>', '?m=poster&c=space&a=create_js&page=' . $page . '&pages=' . $pages);
}
}
/**
* 檢測版位名稱是否存在
*/
public function public_check_space() {
if (!$_GET['name'])
exit(0);
if (pc_base::load_config('system', 'charset') == 'gbk') {
$_GET['name'] = iconv('UTF-8', 'GBK', $_GET['name']);
}
$name = $_GET['name'];
if ($_GET['spaceid']) {
$spaceid = intval($_GET['spaceid']);
$r = $this->db->get_one(array('spaceid' => $spaceid, 'siteid' => $this->get_siteid()));
if ($r['name'] == $name) {
exit('1');
}
}
$r = $this->db->get_one(array('siteid' => $this->get_siteid(), 'name' => $name), 'spaceid');
if ($r['spaceid']) {
exit('0');
} else {
exit('1');
}
}
/**
* 檢查表單數據
* @param Array $data 表單傳遞過來的數組
* @return Array 檢查后的數組
*/
private function check($data = array()) {
if ($data['name'] == '')
showmessage(L('name_plates_not_empty'));
$info = $this->db->get_one(array('name' => $data['name'], 'siteid' => $this->get_siteid()), 'spaceid');
if (($info['spaceid'] && $info['spaceid'] != $_GET['spaceid']) || ($info['spaceid'] && !isset($_GET['spaceid']))) {
showmessage(L('space_exist'), HTTP_REFERER);
}
if ((!isset($data['width']) || $data['width'] == 0) && in_array($data['type'], array('banner', 'fixure', 'float', 'couplet', 'imagechange', 'imagelist'))) {
showmessage(L('plate_width_not_empty'), HTTP_REFERER);
} else {
$data['width'] = intval($data['width']);
}
if ((!isset($data['height']) || $data['height'] == 0) && in_array($data['type'], array('banner', 'fixure', 'float', 'couplet', 'imagechange', 'imagelist'))) {
showmessage(L('plate_height_not_empty'), HTTP_REFERER);
} else {
$data['height'] = intval($data['height']);
}
$TYPES = $this->template_type();
return $data;
}
}
?>
~~~
這里的總結。
廣告位模版配置文件在緩存中,廣告的模版存在于phpcms\templates/default\poster\ 中,它和更新js功能有及其密切的關系。
下面開始分析廣告的js是怎么生成的。
首先看位于 cache/poster_js下的一個已經生成的js文件
名為1.js的文件時對應的數據,位于poster_space表中id為1的記錄,因為這條記錄中path的值為?poster_js/1.js
~~~
function PCMSAD(PID) {
this.ID = PID;
this.PosID = 0;
this.ADID = 0;
this.ADType = "";
this.ADName = "";
this.ADContent = "";
this.PaddingLeft = 0;
this.PaddingTop = 0;
this.Wspaceidth = 0;
this.Height = 0;
this.IsHitCount = "N";
this.UploadFilePath = "";
this.URL = "";
this.SiteID = 0;
this.ShowAD = showADContent;
this.Stat = statAD;
}
function statAD() {
var new_element = document.createElement("script");
new_element.type = "text/javascript";
new_element.src="http://localhost/phpcms952/index.php?m=poster&c=index&a=show&siteid="+this.SiteID+"&spaceid="+this.ADID+"&id="+this.PosID;
document.body.appendChild(new_element);
}
function showADContent() {
var content = this.ADContent;
var str = "";
var AD = eval('('+content+')');
if (this.ADType == "images") {
if (AD.Images[0].imgADLinkUrl) str += "<a href='"+this.URL+'&a=poster_click&sitespaceid='+this.SiteID+"&id="+this.ADID+"&url="+AD.Images[0].imgADLinkUrl+"' target='_blank'>";
str += "<img title='"+AD.Images[0].imgADAlt+"' src='"+this.UploadFilePath+AD.Images[0].ImgPath+"' width='"+this.Width+"' height='"+this.Height+"' style='border:0px;'>";
if (AD.Images[0].imgADLinkUrl) str += "</a>";
}else if(this.ADType == "flash"){
str += "<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' width='"+this.Width+"' height='"+this.Height+"' id='FlashAD_"+this.ADID+"' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0'>";
str += "<param name='movie' value='"+this.UploadFilePath+AD.Images[0].ImgPath+"' />";
str += "<param name='quality' value='autohigh' />";
str += "<param name='wmode' value='opaque'/>";
str += "<embed src='"+this.UploadFilePath+AD.Images[0].ImgPath+"' quality='autohigh' wmode='opaque' name='flashad' swliveconnect='TRUE' pluginspage='http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash' type='application/x-shockwave-flash' width='"+this.Width+"' height='"+this.Height+"'></embed>";
str += "</object>";
}
str += "";
document.write(str);
}
var cmsAD_1 = new PCMSAD('cmsAD_1');
cmsAD_1.PosID = 1;
cmsAD_1.ADID = 1;
cmsAD_1.ADType = "images";
cmsAD_1.ADName = "banner";
cmsAD_1.ADContent = "{'Images':[{'imgADLinkUrl':'http%3A%2F%2Fwww.phpcms.cn','imgADAlt':'','ImgPath':'http://localhost/phpcms952/uploadfile/poster/2.png'}],'imgADLinkTarget':'New','Count':'1','showAlt':'Y'}";
cmsAD_1.URL = "http://localhost/phpcms952/index.php?m=poster&c=index";
cmsAD_1.SiteID = 1;
cmsAD_1.Width = 430;
cmsAD_1.Height = 63;
cmsAD_1.UploadFilePath = '';
cmsAD_1.ShowAD();
var isIE=!!window.ActiveXObject;
if (isIE){
if (document.readyState=="complete"){
cmsAD_1.Stat();
} else {
document.onreadystatechange=function(){
if(document.readyState=="complete") cmsAD_1.Stat();
}
}
} else {
cmsAD_1.Stat();
}
~~~
這是一個類型為banner的廣告模型,我們拿出它的模版文件
~~~
function PCMSAD(PID) {
this.ID = PID;
this.PosID = 0;
this.ADID = 0;
this.ADType = "";
this.ADName = "";
this.ADContent = "";
this.PaddingLeft = 0;
this.PaddingTop = 0;
this.Wspaceidth = 0;
this.Height = 0;
this.IsHitCount = "N";
this.UploadFilePath = "";
this.URL = "";
this.SiteID = 0;
this.ShowAD = showADContent;
this.Stat = statAD;
}
function statAD() {
var new_element = document.createElement("script");
new_element.type = "text/javascript";
new_element.src="{APP_PATH}index.php?m=poster&c=index&a=show&siteid="+this.SiteID+"&spaceid="+this.ADID+"&id="+this.PosID;
document.body.appendChild(new_element);
}
function showADContent() {
var content = this.ADContent;
var str = "";
var AD = eval('('+content+')');
if (this.ADType == "images") {
if (AD.Images[0].imgADLinkUrl) str += "<a href='"+this.URL+'&a=poster_click&sitespaceid='+this.SiteID+"&id="+this.ADID+"&url="+AD.Images[0].imgADLinkUrl+"' target='_blank'>";
str += "<img title='"+AD.Images[0].imgADAlt+"' src='"+this.UploadFilePath+AD.Images[0].ImgPath+"' width='"+this.Width+"' height='"+this.Height+"' style='border:0px;'>";
if (AD.Images[0].imgADLinkUrl) str += "</a>";
}else if(this.ADType == "flash"){
str += "<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' width='"+this.Width+"' height='"+this.Height+"' id='FlashAD_"+this.ADID+"' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0'>";
str += "<param name='movie' value='"+this.UploadFilePath+AD.Images[0].ImgPath+"' />";
str += "<param name='quality' value='autohigh' />";
str += "<param name='wmode' value='opaque'/>";
str += "<embed src='"+this.UploadFilePath+AD.Images[0].ImgPath+"' quality='autohigh' wmode='opaque' name='flashad' swliveconnect='TRUE' pluginspage='http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash' type='application/x-shockwave-flash' width='"+this.Width+"' height='"+this.Height+"'></embed>";
str += "</object>";
}
str += "";
document.write(str);
}
var cmsAD_{$spaceid} = new PCMSAD('cmsAD_{$spaceid}');
cmsAD_{$spaceid}.PosID = {$spaceid};
cmsAD_{$spaceid}.ADID = {$p_id};
cmsAD_{$spaceid}.ADType = "{$p_type}";
cmsAD_{$spaceid}.ADName = "{$p_name}";
cmsAD_{$spaceid}.ADContent = "{'Images':[{'imgADLinkUrl':'{urlencode($p_setting[1]['linkurl'])}','imgADAlt':'{$p_setting[1]['alt']}','ImgPath':'<?php echo $p_type=='images' ? $p_setting[1]['imageurl'] : $p_setting[1]['flashurl'];?>'}],'imgADLinkTarget':'New','Count':'1','showAlt':'Y'}";
cmsAD_{$spaceid}.URL = "{APP_PATH}index.php?m=poster&c=index";
cmsAD_{$spaceid}.SiteID = {$siteid};
cmsAD_{$spaceid}.Width = {$width};
cmsAD_{$spaceid}.Height = {$height};
cmsAD_{$spaceid}.UploadFilePath = '';
cmsAD_{$spaceid}.ShowAD();
var isIE=!!window.ActiveXObject;
if (isIE){
if (document.readyState=="complete"){
cmsAD_{$spaceid}.Stat();
} else {
document.onreadystatechange=function(){
if(document.readyState=="complete") cmsAD_{$spaceid}.Stat();
}
}
} else {
cmsAD_{$spaceid}.Stat();
}
~~~
這樣,給我們的認識就是,模版上的變量被替換了,并重新生成了js文件,放到了相應的文件夾。
~~~
<?php
/**
*
* @param 廣告生成js類
*/
defined('IN_PHPCMS') or exit('No permission resources.');
class html {
private $db, $s_db, $queue;
/**
*
* 類的構造函數讀取了三個模型作為了類的內部變量
* 廣告位,廣告,隊列
*
* 這里提一下隊列模型
*
* phpcms的隊列模型,就是在任務太多的情況下
* 將其存入名為queue的表中
* 處理完一個刪除一個
* 可以理解為排隊機制
*
*/
public function __construct() {
$this->s_db = pc_base::load_model('poster_space_model');
$this->db = pc_base::load_model('poster_model');
$this->queue = pc_base::load_model('queue_model');
}
/**
* 生成廣告js文件
* @param intval $id 廣告版位ID
* @return boolen 成功返回true
*/
public function create_js($id = 0) {
$id = intval($id);
if (!$id) {
$this->msg = L('no_create_js');
return false;
}
$siteid = get_siteid();
/**
*
* 這里的生成js文件就是單一的
* 在上文提到的調用中循環采用了這個
* 所以下面拿到的是當前站點id下的廣告位的數據
*
*/
$r = $this->s_db->get_one(array('siteid' => $siteid, 'spaceid' => $id));
$now = SYS_TIME; //將系統時間寫入變量
if ($r['setting'])
$space_setting = string2array($r['setting']); //如果存在廣告位的設置,就轉化成數組,其實肯定存在的
if ($r['type'] == 'code')
return true; //代碼類型的就直接返回了,因為不用生產js文件
$poster_template = getcache('poster_template_' . $siteid, 'commons'); //讀取了廣告模版設置的緩存
/**
*
* 下面進行一個判斷
*
* 判斷廣告位的類型配置是不是存在option一項
*
*
*/
if ($poster_template[$r['type']]['option']) {
/**
* 如果存在
* 獲取
* 當前站點 當前廣告位 能使用 設置時間在當前時間內 , 按照 人為排序正序 id倒序
* 的所有廣告
*
* 并且打散數組
*/
$where = "`spaceid`='" . $id . "' AND `siteid`='" . $siteid . "' AND `disabled`=0 AND `startdate`<='" . $now . "' AND (`enddate`>='" . $now . "' OR `enddate`=0) ";
$pinfo = $this->db->select($where, '*', '', '`listorder` ASC, `id` DESC');
if (is_array($pinfo) && !empty($pinfo)) {
foreach ($pinfo as $k => $rs) {
if ($rs['setting']) {
$rs['setting'] = string2array($rs['setting']);
$pinfo[$k] = $rs;
} else {
unset($pinfo[$k]);
}
}
extract($r);
} else {
return true;
}
} else {
/**
* 如果不存在
*
* 取出數據的方式和上面一致
*
* 但是在打散的數組的每個變量前面都加上了 P
*
* 所以對于該廣告模塊來說,充分使用了extract這個函數
*
* 有興趣的同學可以研究下
*
*/
$where = " `spaceid`='" . $id . "' AND `siteid`='" . $siteid . "' AND `disabled`=0 AND `startdate`<='" . $now . "' AND (`enddate`>='" . $now . "' OR `enddate`=0)";
$pinfo = $this->db->get_one($where, '*', '`listorder` ASC, `id` DESC');
if (is_array($pinfo) && $pinfo['setting']) {
$pinfo['setting'] = string2array($pinfo['setting']);
}
extract($r);
if (!is_array($pinfo) || empty($pinfo))
return true;
extract($pinfo, EXTR_PREFIX_SAME, 'p');
}
$file = CACHE_PATH . $path;
/**
*
* 這里用的ob函數進行輸出
*
* 優點:不會因為php文件提前輸出header而出錯,又可以及時刷新緩存區而不浪費資源
*/
ob_start();
/**
*
* 這里在文件輸出流中引入了廣告模版文件
* 而在原始的模版文件中存在著大量的php變量
* 這些變量和上面被打散的數組中的變量是一致的
* 也就是說在這一步
* 變量被巧妙的替換了
* 很自然的轉化成了js文件
*/
include template('poster', $type);
$data = ob_get_contents();
/**
*
* 將合并后的文件內容存進變量后清空了ob文件流
*/
ob_end_clean();
/**
*
* 最后根據路徑寫入文件
*/
$strlen = pc_base::load_config('system', 'lock_ex') ? file_put_contents($file, $data, LOCK_EX) : file_put_contents($file, $data);
@chmod($file, 0777);
return true;
}
}
?>
~~~
### 四、總結
根據上面的圖文注釋,小伙伴們都可以清楚的知道phpcms的廣告是怎么產生的了吧。
配置文件+模版文件+數據庫中具體數據=js廣告文件
### 五、后記
用了一晚上的時間,又重新分析了一下phpcms,這個功能原來在大連實訓的時候寫過,也是參考phpcms的,這回也算是復習吧。
溫故知新,回頭再看phpcms,還是有很多值得學習的。
看來有空還要研究下它的隊列機制了。
- 前言
- php編寫RSS源
- PHP編寫rss源(續)
- ubuntu 上給PHP安裝擴展 Msgpack 和 Yar
- PHPCMS廣告模塊詳細分析——廣告的生成
- Yii配合Yar在php5.3.3環境下的錯誤以及解決方案
- 【Yaf】Yaf的環境安裝遇到的問題以及解決方案
- 【PHP擴展】centos給PHP安裝擴展
- 【MYSQL】PHPMYADMIN出現的問題以及解決方案
- 【PHP】阿里云升級PHP到5.5詳解
- 【phpMyAdmin】修改配置文件連接到其他服務器
- 【PHP】PHP5.4.0版本ChangeLog詳解(上)
- 【PHP】編譯安裝 PHP5.6.13遇到問題以及解決方案
- 【翻譯】PHP7——新特性
- 【PHP】數組foreach引發的小問題
- 【CURL】PHP的CURL開發項目最佳實踐
- 【PHP】PHP轉換圖片為ico格式源碼
- 【PHP】PHP圖像裁剪縮略裁切類源代碼及使用方法