목차
phpcms V9 首页模板文件解析(转),
php教程 php手册 phpcms V9 首页模板文件解析(转),

phpcms V9 首页模板文件解析(转),

Jul 06, 2016 pm 02:24 PM
http phpcms 문서 주형 분석하다 변화 첫 페이지

phpcms V9 首页模板文件解析(转),

转自:http://www.cnblogs.com/Braveliu/p/5100018.html

转在了解了《phpcms V9 URL访问解析》之后,我们已经知道首页最终执行的是content模块下index控制器的init方法。

下面, 我们逐步分析过程如下:

第一、首页默认执行的是index.php?m=content&c=index&a=init

如下代码(路径:phpcms\modules\content\index.php),先从init函数分析:

 1 class index 
 2 {
 3     private $db;
 4     function __construct() 
 5     {
 6         $this->db = pc_base::load_model('content_model');
 7         $this->_userid = param::get_cookie('_userid');
 8         $this->_username = param::get_cookie('_username');
 9         $this->_groupid = param::get_cookie('_groupid');
10     }
11     //首页
12     public function init() 
13     {
14         if(isset($_GET['siteid'])) 
15         {
16             $siteid = intval($_GET['siteid']); //当前站点id  函数intval作用变量转成整数类型
17         } 
18         else 
19         {
20             $siteid = 1;
21         }
22         $siteid = $GLOBALS['siteid'] = max($siteid,1);
23         define('SITEID', $siteid);
24         $_userid = $this->_userid;
25         $_username = $this->_username;
26         $_groupid = $this->_groupid;
27         //SEO 搜索引擎优化信息
28         $SEO = seo($siteid); //调用第二步,获取当前站点当前栏目下生成的SEO信息
29         $sitelist  = getcache('sitelist','commons'); //缓存后台设置的所有站点配置信息
30         $default_style = $sitelist[$siteid]['default_style']; //当前站点默认模板风格配置
31         $CATEGORYS = getcache('category_content_'.$siteid,'commons'); //当前站点所有栏目详细配置信息
32         include template('content','index',$default_style); //调用第三步:模板调用
33     }
로그인 후 복사

第二、获取SEO信息:phpcms/libs/functions/global.func.php

 1 /**
 2  * 生成SEO
 3  * @param $siteid       站点ID
 4  * @param $catid        栏目ID
 5  * @param $title        标题
 6  * @param $description  描述
 7  * @param $keyword      关键词
 8  */
 9 function seo($siteid, $catid = '', $title = '', $description = '', $keyword = '') 
10 {
11     if (!empty($title))
12         $title = strip_tags($title); //过滤title。 strip_tags() 函数剥去字符串中的 HTML、XML 以及 PHP 的标签。
13     if (!empty($description)) 
14         $description = strip_tags($description); //过滤description
15     if (!empty($keyword)) 
16         $keyword = str_replace(' ', ',', strip_tags($keyword)); //过滤keyword
17     $sites = getcache('sitelist', 'commons'); //获取所有站点详细配置信息
18     $site = $sites[$siteid];    //当前站点详细配置信息
19     $cat = array();
20     if (!empty($catid))     //栏目ID不为空
21     {
22         $siteids = getcache('category_content','commons'); //获取所有栏目对应的站点ID缓存文件,格式:栏目ID=>站点ID
23         $siteid = $siteids[$catid]; //当前栏目对应的站点ID
24         $categorys = getcache('category_content_'.$siteid,'commons'); //获取当前站点下所有栏目的详细配置信息
25         $cat = $categorys[$catid];    //当前站点下当前栏目的详细配置信息 
26         $cat['setting'] = string2array($cat['setting']); //当前站点当前栏目详细配置信息的setting设置信息,转化为数组
27     }
28     //站点title
29     $seo['site_title'] =isset($site['site_title']) && !empty($site['site_title']) ? $site['site_title'] : $site['name'];
30     //关键字
31     $seo['keyword'] = !empty($keyword) ? $keyword : $site['keywords'];
32     //描述
33     $seo['description'] = isset($description) && !empty($description) ? $description : (isset($cat['setting']['meta_description']) && !empty($cat['setting']['meta_description']) ? $cat['setting']['meta_description'] : (isset($site['description']) && !empty($site['description']) ? $site['description'] : ''));
34     //标题
35     $seo['title'] =  (isset($title) && !empty($title) ? $title.' - ' : '').(isset($cat['setting']['meta_title']) && !empty($cat['setting']['meta_title']) ? $cat['setting']['meta_title'].' - ' : (isset($cat['catname']) && !empty($cat['catname']) ? $cat['catname'].' - ' : ''));
36     foreach ($seo as $k=>$v) 
37     {
38         $seo[$k] = str_replace(array("\n","\r"),    '', $v); //将seo信息中\n和\r替换为空
39     }
40     return $seo;    //返回seo数组信息
41 }
로그인 후 복사

第三、模板调用:phpcms/libs/functions/global.func.php

 1 /**
 2  * 模板调用
 3  *
 4  * @param $module 默认为content
 5  * @param $template 默认为index
 6  * @param $istag
 7  * @return unknown_type
 8  */
 9 function template($module = 'content', $template = 'index', $style = '') 
10 {
11     if(strpos($module, 'plugin/')!== false) 
12     { // 检测模块里面是否包含plugin字符,这里进行了对插件模板的判断,插件模板需要调用p_template过程解析
13         $plugin = str_replace('plugin/', '', $module);
14         return p_template($plugin, $template,$style);
15     }
16     $module = str_replace('/', DIRECTORY_SEPARATOR, $module);
17     if(!empty($style) && preg_match('/([a-z0-9\-_]+)/is',$style)) 
18     {
19     } 
20     elseif (empty($style) && !defined('STYLE')) 
21     {
22         if(defined('SITEID'))  // 是否定义了SITEID常量
23         {
24             $siteid = SITEID;
25         } 
26         else 
27         {
28             $siteid = param::get_cookie('siteid');
29         }
30         if (!$siteid) $siteid = 1;
31         $sitelist = getcache('sitelist','commons'); //获取所有站点的详细配置信息
32         if(!empty($siteid)) 
33         {
34             $style = $sitelist[$siteid]['default_style']; //获取当前站点的默认模板风格
35         }
36     } 
37     elseif (empty($style) && defined('STYLE')) 
38     {
39         $style = STYLE;
40     } 
41     else 
42     {
43         $style = 'default';
44     }
45     if(!$style) 
46         $style = 'default';
47     //模板解析类,文件路径:phpcms/libs/classes/template_cache.class.php
48     $template_cache = pc_base::load_sys_class('template_cache');
49     //编译文件缓存路径:根目录/caches/caches_template/default/content/index.php
50     $compiledtplfile = PHPCMS_PATH.'caches'.DIRECTORY_SEPARATOR.'caches_template'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.php';
51     //首页模板文件,如文件路径:phpcms/templates/dafault/content/index.html
52     if(file_exists(PC_PATH.'templates'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html')) 
53     {
54         //如果编译文件不存在或者说模板文件的创建时间大于编译文件的生成时间,则重新编译
55         if(!file_exists($compiledtplfile) || (@filemtime(PC_PATH.'templates'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html') > @filemtime($compiledtplfile))) 
56         {
57             $template_cache->template_compile($module, $template, $style); //调用第四步:适用模板风格不是default的情况
58         }
59     } 
60     else 
61     {
62         //编译文件缓存路径:根目录/caches/caches_template/default/content/index.php 
63         $compiledtplfile = PHPCMS_PATH.'caches'.DIRECTORY_SEPARATOR.'caches_template'.DIRECTORY_SEPARATOR.'default'.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.php';
64         //如果编译文件不存在或者说前台公共的模板文件存在,并且前台公共模板文件的创建时间大于编译文件的生成时间
65         if(!file_exists($compiledtplfile) || (file_exists(PC_PATH.'templates'.DIRECTORY_SEPARATOR.'default'.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html') && filemtime(PC_PATH.'templates'.DIRECTORY_SEPARATOR.'default'.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html') > filemtime($compiledtplfile))) 
66         {
67             //重新编译
68             $template_cache->template_compile($module, $template, 'default');
69         } 
70         elseif (!file_exists(PC_PATH.'templates'.DIRECTORY_SEPARATOR.'default'.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html')) 
71         {  //如果前台公共的模板文件不存在的话,则提示模板不存在
72             showmessage('Template does not exist.'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html');
73         }
74     }
75     //返回编译文件
76     return $compiledtplfile;
77 }
로그인 후 복사

第四、模板解析:phpcms/libs/classes/template_cache.class.php

 1 /**
 2  *  模板解析缓存
 3  */
 4 final class template_cache 
 5 {
 6     
 7     /**
 8      * 编译模板
 9      *
10      * @param $module    模块名称
11      * @param $template    模板文件名
12      * @param $istag    是否为标签模板
13      * @return unknown
14      */
15     
16     public function template_compile($module, $template, $style = 'default') 
17     {
18         if(strpos($module, '/')=== false) // 如果“/”不存在
19         {
20             //路径:phpcms/templates/default/content/index.html 如:首页公共模板文件  
21             $tplfile = $_tpl = PC_PATH.'templates'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html';
22         } 
23         elseif (strpos($module, 'yp/') !== false) 
24         {
25             $module = str_replace('/', DIRECTORY_SEPARATOR, $module);
26             $tplfile = $_tpl = PC_PATH.'templates'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html';
27         } 
28         else 
29         {
30             $plugin = str_replace('plugin/', '', $module);
31             $module = str_replace('/', DIRECTORY_SEPARATOR, $module);
32             $tplfile = $_tpl = PC_PATH.'plugin'.DIRECTORY_SEPARATOR.$plugin.DIRECTORY_SEPARATOR.'templates'.DIRECTORY_SEPARATOR.$template.'.html';
33         }
34         if ($style != 'default' && !file_exists ( $tplfile )) 
35         {
36             $style = 'default';
37             $tplfile = PC_PATH.'templates'.DIRECTORY_SEPARATOR.'default'.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html';
38         }
39         if (! file_exists ( $tplfile ))
40         {
41             //如果公共模板文件不存在,则提示模板文件不存在,如:/templates/default/content/index.html is not exists!
42             showmessage ( "templates".DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.".html is not exists!" );
43         }
44         //获取公共模板文件中的内容
45         $content = @file_get_contents ( $tplfile );
46         //要生成的编译文件所在目录
47         $filepath = CACHE_PATH.'caches_template'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR;
48         if(!is_dir($filepath)) 
49         {
50             //如果目录不存在,则层级创建所有目录
51             mkdir($filepath, 0777, true);
52         }
53         //编译文件的全路径
54         $compiledtplfile = $filepath.$template.'.php';
55         //解析公共模板文件中的内容及标签,并返回解析后的内容  
56         $content = $this->template_parse($content); // 调用下一个过程
57         //将解析后的公共模板文件内容写入到要生成的编译文件中
58         $strlen = file_put_contents ( $compiledtplfile, $content );
59         //给生成的编译文件设置权限
60         chmod ( $compiledtplfile, 0777 );
61         //返回写入编译文件的字节数
62         return $strlen;
63     }
64 
65     /**
66      * 解析模板
67      *
68      * @param $str    模板内容
69      * @return ture
70      */
71     public function template_parse($str) {
72         $str = preg_replace ( "/\{template\s+(.+)\}/", "<?php include template(\\1); ?>", $str );
73         $str = preg_replace ( "/\{include\s+(.+)\}/", "<?php include \\1; ?>", $str );
74         $str = preg_replace ( "/\{php\s+(.+)\}/", "<?php \\1?>", $str );
75         $str = preg_replace ( "/\{if\s+(.+?)\}/", "<?php if(\\1) { ?>", $str );
76         $str = preg_replace ( "/\{else\}/", "<?php } else { ?>", $str );
77         $str = preg_replace ( "/\{elseif\s+(.+?)\}/", "<?php } elseif (\\1) { ?>", $str );
78         $str = preg_replace ( "/\{\/if\}/", "<?php } ?>", $str );
79         //for 循环
80         $str = preg_replace("/\{for\s+(.+?)\}/","<?php for(\\1) { ?>",$str);
81         $str = preg_replace("/\{\/for\}/","<?php } ?>",$str);
82         //++ --
83         $str = preg_replace("/\{\+\+(.+?)\}/","<?php ++\\1; ?>",$str);
84         $str = preg_replace("/\{\-\-(.+?)\}/","<?php ++\\1; ?>",$str);
85         $str = preg_replace("/\{(.+?)\+\+\}/","<?php \\1++; ?>",$str);
86         $str = preg_replace("/\{(.+?)\-\-\}/","<?php \\1--; ?>",$str);
87         $str = preg_replace ( "/\{loop\s+(\S+)\s+(\S+)\}/", "<?php \$n=1;if(is_array(\\1)) foreach(\\1 AS \\2) { ?>", $str );
88         $str = preg_replace ( "/\{loop\s+(\S+)\s+(\S+)\s+(\S+)\}/", "<?php \$n=1; if(is_array(\\1)) foreach(\\1 AS \\2 => \\3) { ?>", $str );
89         $str = preg_replace ( "/\{\/loop\}/", "<?php \$n++;}unset(\$n); ?>", $str );
90         $str = preg_replace ( "/\{([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff:]*\(([^{}]*)\))\}/", "<?php echo \\1;?>", $str );
91         $str = preg_replace ( "/\{\\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff:]*\(([^{}]*)\))\}/", "<?php echo \\1;?>", $str );
92         $str = preg_replace ( "/\{(\\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\}/", "<?php echo \\1;?>", $str );
93         $str = preg_replace("/\{(\\$[a-zA-Z0-9_\[\]\'\"\$\x7f-\xff]+)\}/es", "\$this->addquote('<?php echo \\1;?>')",$str);
94         $str = preg_replace ( "/\{([A-Z_\x7f-\xff][A-Z0-9_\x7f-\xff]*)\}/s", "<?php echo \\1;?>", $str );
95         $str = preg_replace("/\{pc:(\w+)\s+([^}]+)\}/ie", "self::pc_tag('$1','$2', '$0')", $str);
96         $str = preg_replace("/\{\/pc\}/ie", "self::end_pc_tag()", $str);
97         $str = "<?php defined('IN_PHPCMS') or exit('No permission resources.'); ?>" . $str;
98         return $str;
99     }
로그인 후 복사

第五、PC标签的解析:phpcms/libs/classes/template_cache.class.php 文件

  1 /**
  2      * 解析PC标签
  3      * @param string $op 操作方式
  4      * @param string $data 参数
  5      * @param string $html 匹配到的所有的HTML代码
  6      */
  7     public static function pc_tag($op, $data, $html) 
  8     {
  9         preg_match_all("/([a-z]+)\=[\"]?([^\"]+)[\"]?/i", stripslashes($data), $matches, PREG_SET_ORDER);
 10         $arr = array('action','num','cache','page', 'pagesize', 'urlrule', 'return', 'start');
 11         $tools = array('json', 'xml', 'block', 'get');
 12         $datas = array();
 13         $tag_id = md5(stripslashes($html));
 14         //可视化条件
 15         $str_datas = 'op='.$op.'&tag_md5='.$tag_id;
 16         foreach ($matches as $v) 
 17         {
 18             $str_datas .= $str_datas ? "&$v[1]=".($op == 'block' && strpos($v[2], '$') === 0 ? $v[2] : urlencode($v[2])) : "$v[1]=".(strpos($v[2], '$') === 0 ? $v[2] : urlencode($v[2]));
 19             if(in_array($v[1], $arr)) 
 20             {
 21                 $$v[1] = $v[2];//如果pc标签中参数在默认参数数组$arr中存在,则将参数转换为变量,如:$page=value等 
 22                 continue;
 23             }
 24             $datas[$v[1]] = $v[2];//如果pc标签中参数不在默认参数数组$arr中存在,则直接将其放置到$datas[参数名]=value中 
 25         }
 26         $str = '';
 27         $num = isset($num) && intval($num) ? intval($num) : 20;
 28         $cache = isset($cache) && intval($cache) ? intval($cache) : 0;
 29         $return = isset($return) && trim($return) ? trim($return) : 'data';
 30         if (!isset($urlrule)) $urlrule = '';
 31         if (!empty($cache) && !isset($page)) 
 32         {
 33             $str .= '$tag_cache_name = md5(implode(\'&\','.self::arr_to_html($datas).').\''.$tag_id.'\');if(!$'.$return.' = tpl_cache($tag_cache_name,'.$cache.')){';
 34         }
 35         if (in_array($op,$tools)) 
 36         { //pc标签分两大类:工具类和模块类。工具类执行如下代码
 37             switch ($op) 
 38             {
 39                 case 'json':
 40                         if (isset($datas['url']) && !empty($datas['url'])) 
 41                         {
 42                             $str .= '$json = @file_get_contents(\''.$datas['url'].'\');';
 43                             $str .= '$'.$return.' = json_decode($json, true);';
 44                         }
 45                     break;
 46                     
 47                 case 'xml':
 48                         $str .= '$xml = pc_base::load_sys_class(\'xml\');';
 49                         $str .= '$xml_data = @file_get_contents(\''.$datas['url'].'\');';
 50                         $str .= '$'.$return.' = $xml->xml_unserialize($xml_data);';
 51                     break;
 52                     
 53                 case 'get':
 54                         $str .= 'pc_base::load_sys_class("get_model", "model", 0);';
 55                         if ($datas['dbsource']) 
 56                         {
 57                             $dbsource = getcache('dbsource', 'commons');
 58                             if (isset($dbsource[$datas['dbsource']])) 
 59                             {
 60                                 $str .= '$get_db = new get_model('.var_export($dbsource,true).', \''.$datas['dbsource'].'\');';
 61                             } 
 62                             else 
 63                             {
 64                                 return false;
 65                             }
 66                         } 
 67                         else 
 68                         {
 69                             $str .= '$get_db = new get_model();';
 70                         }
 71                         $num = isset($num) && intval($num) > 0 ? intval($num) : 20;
 72                         if (isset($start) && intval($start)) 
 73                         {
 74                             $limit = intval($start).','.$num;
 75                         } 
 76                         else 
 77                         {
 78                             $limit = $num;
 79                         }
 80                         if (isset($page)) 
 81                         {
 82                             $str .= '$pagesize = '.$num.';';
 83                             $str .= '$page = intval('.$page.') ? intval('.$page.') : 1;if($page<=0){$page=1;}';
 84                             $str .= '$offset = ($page - 1) * $pagesize;';
 85                             $limit = '$offset,$pagesize';
 86                             $sql = 'SELECT COUNT(*) as count FROM ('.$datas['sql'].') T';
 87                             $str .= '$r = $get_db->sql_query("'.$sql.'");$s = $get_db->fetch_next();$pages=pages($s[\'count\'], $page, $pagesize, $urlrule);';
 88                         }
 89                         
 90                         $str .= '$r = $get_db->sql_query("'.$datas['sql'].' LIMIT '.$limit.'");while(($s = $get_db->fetch_next()) != false) {$a[] = $s;}$'.$return.' = $a;unset($a);';
 91                     break;
 92                     
 93                 case 'block':
 94                     $str .= '$block_tag = pc_base::load_app_class(\'block_tag\', \'block\');';
 95                     $str .= 'echo $block_tag->pc_tag('.self::arr_to_html($datas).');';
 96                     break;
 97             }
 98         } 
 99         else 
100         {    //pc标签分两大类:工具类和模块类。模块类执行如下代码
101             if (!isset($action) || empty($action)) 
102                 return false;
103             //content模块:phpcms/modules/content/classes/content_tag.class.php  
104             if (module_exists($op) && file_exists(PC_PATH.DIRECTORY_SEPARATOR.'modules'.DIRECTORY_SEPARATOR.$op.DIRECTORY_SEPARATOR.'classes'.DIRECTORY_SEPARATOR.$op.'_tag.class.php')) 
105             {
106                 //content_tag.class.php  检查content_tag类中是否存在的某方法
107                 $str .= '$'.$op.'_tag = pc_base::load_app_class("'.$op.'_tag", "'.$op.'");if (method_exists($'.$op.'_tag, \''.$action.'\')) {';    
108                 if (isset($start) && intval($start)) 
109                 {
110                     $datas['limit'] = intval($start).','.$num; //如:limit 0 , 10
111                 } 
112                 else 
113                 {
114                     $datas['limit'] = $num; //如:limit 10
115                 }
116                 if (isset($page)) //分页参数
117                 {
118                     $str .= '$pagesize = '.$num.';'; //每页显示数据量
119                     $str .= '$page = intval('.$page.') ? intval('.$page.') : 1;if($page<=0){$page=1;}';//当前页码
120                     $str .= '$offset = ($page - 1) * $pagesize;';//要查询数据的开始位置
121                     $datas['limit'] = '$offset.",".$pagesize';
122                     $datas['action'] = $action; //方法,如,content_tag.class.php中的lists方法 
123                     $str .= '$'.$op.'_total = $'.$op.'_tag->count('.self::arr_to_html($datas).');';//分页方法
124                     $str .= '$pages = pages($'.$op.'_total, $page, $pagesize, $urlrule);';
125                 }
126                 //调用第七步:content_tag.class.php中方法
127                 $str .= '$'.$return.' = $'.$op.'_tag->'.$action.'('.self::arr_to_html($datas).');';
128                 $str .= '}';
129             } 
130         }
131         if (!empty($cache) && !isset($page)) 
132         {
133             $str .= 'if(!empty($'.$return.')){setcache($tag_cache_name, $'.$return.', \'tpl_data\');}';
134             $str .= '}';
135         }
136         /**  
137          * 解析结果大概如下所示:  
138          <?php  
139          if(defined('IN_ADMIN')  && !defined('HTML')) 
140          {  
141             echo "<div class=\"admin_piao\" pc_action=\"content\" data=\"op=content&tag_md5=2d4b9e3c7c2cc4bd0cec8b1fac9ae764&action=position&posid=12&thumb=1&order=listorder+DESC&num=10\">  
142             <a href=\"javascript:void(0)\" class=\"admin_piao_edit\">编辑</a>";  
143          }  
144          $content_tag = pc_base::load_app_class("content_tag", "content");  
145          if (method_exists($content_tag, 'position')) 
146          {  
147             $data = $content_tag->position(array('posid'=>'12','thumb'=>'1','order'=>'listorder DESC','limit'=>'10',));  
148          }
149         ?>
150          */
151         return "<"."?php if(defined('IN_ADMIN')  && !defined('HTML')) {echo \"<div class=\\\"admin_piao\\\" pc_action=\\\"".$op."\\\" data=\\\"".$str_datas."\\\"><a href=\\\"javascript:void(0)\\\" class=\\\"admin_piao_edit\\\">".($op=='block' ? L('block_add') : L('edit'))."</a>\";}".$str."?".">";
152     }
로그인 후 복사

第六、PC标签类。文件路径:phpcms/modules/content/classes/content_tag.class.php

  1 class content_tag 
  2 {
  3     private $db;
  4     public function __construct() 
  5     {
  6         $this->db = pc_base::load_model('content_model'); //调用第七步,数据模型,对应数据表为news和news_data
  7         $this->position = pc_base::load_model('position_data_model'); //数据模型
  8     }
  9     /**
 10      * 初始化模型
 11      * @param $catid
 12      */
 13     public function set_modelid($catid) 
 14     {
 15         static $CATS;
 16         $siteids = getcache('category_content','commons'); //获取所有栏目所属的站点id
 17         if(!$siteids[$catid]) 
 18             return false; //不存在此栏目,返回false
 19         $siteid = $siteids[$catid]; //当前栏目所属站点id
 20         if ($CATS[$siteid]) 
 21         {
 22             $this->category = $CATS[$siteid];
 23         } 
 24         else 
 25         {
 26             //获取当前站点id下所有栏目的配置信息
 27             $CATS[$siteid] = $this->category = getcache('category_content_'.$siteid,'commons');
 28         }
 29         if($this->category[$catid]['type']!=0) 
 30             return false; //如果不为内部栏目,返回false  0-内部栏目 1-单网页 2-外部链接
 31         $this->modelid = $this->category[$catid]['modelid']; //获取当前栏目所属模型id 
 32         $this->db->set_model($this->modelid); //调用第七步
 33         $this->tablename = $this->db->table_name; //数据表名
 34         if(empty($this->category)) 
 35         {
 36             //当前站点id下所有栏目的配置信息
 37             return false;
 38         } 
 39         else
 40         {
 41             return true;
 42         }
 43     }
 44     /**
 45      * 分页统计
 46      * @param $data
 47      */
 48     public function count($data) 
 49     {
 50         if($data['action'] == 'lists') 
 51         {
 52             $catid = intval($data['catid']);
 53             if(!$this->set_modelid($catid)) return false;
 54             if(isset($data['where'])) 
 55             {
 56                 $sql = $data['where'];
 57             } 
 58             else 
 59             {
 60                 if($this->category[$catid]['child']) 
 61                 {
 62                     $catids_str = $this->category[$catid]['arrchildid'];
 63                     $pos = strpos($catids_str,',')+1;
 64                     $catids_str = substr($catids_str, $pos);
 65                     $sql = "status=99 AND catid IN ($catids_str)";
 66                 } 
 67                 else 
 68                 {
 69                     $sql = "status=99 AND catid='$catid'";
 70                 }
 71             }
 72             return $this->db->count($sql);
 73         }
 74     }
 75     
 76     /**
 77      * 列表页标签
 78      * @param $data
 79      */
 80     public function lists($data) 
 81     {
 82         $catid = intval($data['catid']);
 83         if(!$this->set_modelid($catid)) 
 84             return false;
 85         if(isset($data['where'])) //如果pc标签中设置了条件
 86         {
 87             $sql = $data['where']; //pc标签中的条件
 88         } 
 89         else 
 90         {
 91             $thumb = intval($data['thumb']) ? " AND thumb != ''" : '';
 92             if($this->category[$catid]['child']) 
 93             {
 94                 $catids_str = $this->category[$catid]['arrchildid'];
 95                 $pos = strpos($catids_str,',')+1;
 96                 $catids_str = substr($catids_str, $pos);
 97                 $sql = "status=99 AND catid IN ($catids_str)".$thumb;
 98             } 
 99             else 
100             {
101                 $sql = "status=99 AND catid='$catid'".$thumb;
102             }
103         }
104         $order = $data['order']; //pc标签中排序字段
105 
106         //从数据库中获取主表数据,使用的也是sql语句查询
107         $return = $this->db->select($sql, '*', $data['limit'], $order, '', 'id');
108                         
109         //调用副表的数据
110         if (isset($data['moreinfo']) && intval($data['moreinfo']) == 1) 
111         {
112             $ids = array();
113             foreach ($return as $v) 
114             {
115                 if (isset($v['id']) && !empty($v['id'])) 
116                 {
117                     $ids[] = $v['id'];
118                 } 
119                 else
120                 {
121                     continue;
122                 }
123             }
124             if (!empty($ids)) 
125             {
126                 $this->db->table_name = $this->db->table_name.'_data';//副表名
127                 $ids = implode('\',\'', $ids);
128                 $r = $this->db->select("`id` IN ('$ids')", '*', '', '', '', 'id');
129                 if (!empty($r)) 
130                 {
131                     foreach ($r as $k=>$v) 
132                     {
133                         if (isset($return[$k])) 
134                             $return[$k] = array_merge($v, $return[$k]); //主表中数据与副表中数据合并
135                     }
136                 }
137             }
138         }
139         return $return;  //返回查询到的数据
140     }
로그인 후 복사

注意:由以上分析可知,pc标签内部原理也是通过sql语句来获取数据的。

另外,PC标签分模块来使用,内容模块PC标签可用来完成如下功能:

(1)获取内容列表:lists 方法 (如上)

(2)获取点击排行榜:hits 方法 (详细见文件content_tag.class.php)

(3)获取相关文章:relation 方法 (详细见文件content_tag.class.php)

(4)获取栏目列表:category 方法 (详细见文件content_tag.class.php)

第七、content_model类。文件路径:phpcms/model/content_model.class.php

 1 /**
 2  * 内容模型数据库操作类
 3  */
 4 pc_base::load_sys_class('model', '', 0);
 5 class content_model extends model 
 6 {
 7     public $table_name = ''; // 数据库表名
 8     public $category = ''; // 栏目
 9     public function __construct() 
10     {
11         $this->db_config = pc_base::load_config('database');  //加载数据库配置信息
12         $this->db_setting = 'default'; // 加载数据库默认的配置信息
13         parent::__construct();  // 调用父类的构造函数
14         $this->url = pc_base::load_app_class('url', 'content');
15         $this->siteid = get_siteid(); //获取当前站点id
16     }
17     public function set_model($modelid)
18     {
19         //获取所有模型的配置信息  1-文档模型 2-下载模型 3-图片模型  跟后台设置有关
20         $this->model = getcache('model', 'commons');
21         //当前模型id
22         $this->modelid = $modelid;
23         //模型所对应的数据表(文档模型->news  图片模型->picture 下载模型->download) 
24         $this->table_name = $this->db_tablepre.$this->model[$modelid]['tablename'];
25         $this->model_tablename = $this->model[$modelid]['tablename'];
26     }
로그인 후 복사

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

0x80004005 오류 코드가 나타나는 경우 수행할 작업 편집기에서 0x80004005 오류 코드를 해결하는 방법을 알려줍니다. 0x80004005 오류 코드가 나타나는 경우 수행할 작업 편집기에서 0x80004005 오류 코드를 해결하는 방법을 알려줍니다. Mar 21, 2024 pm 09:17 PM

컴퓨터에서 폴더를 삭제하거나 압축을 풀 때 "오류 0x80004005: 지정되지 않은 오류"라는 프롬프트 대화 상자가 나타나는 경우가 있습니다. 이러한 상황이 발생하면 어떻게 해야 합니까? 실제로 오류 코드 0x80004005가 나타나는 데에는 여러 가지 이유가 있지만 대부분은 바이러스로 인해 발생합니다. 문제를 해결하기 위해 dll을 다시 등록할 수 있습니다. 아래에서는 편집기에서 0x80004005 오류 코드를 처리한 경험을 설명합니다. . 일부 사용자는 컴퓨터를 사용할 때 오류 코드 0X80004005가 표시됩니다. 0x80004005 오류는 주로 컴퓨터가 특정 동적 링크 라이브러리 파일을 올바르게 등록하지 않거나 컴퓨터와 인터넷 간의 HTTPS 연결을 허용하지 않는 방화벽으로 인해 발생합니다. 그렇다면 어떨까요?

PHP에서 중간점의 의미와 사용법 분석 PHP에서 중간점의 의미와 사용법 분석 Mar 27, 2024 pm 08:57 PM

[PHP 중간점의 의미와 사용법 분석] PHP에서 중간점(.)은 두 개의 문자열이나 객체의 속성이나 메소드를 연결하는 데 사용되는 일반적으로 사용되는 연산자입니다. 이 기사에서는 구체적인 코드 예제를 통해 PHP에서 중간점의 의미와 사용법을 자세히 살펴보겠습니다. 1. 문자열 중간점 연산자 연결 PHP에서 가장 일반적인 사용법은 두 문자열을 연결하는 것입니다. 두 문자열 사이에 .을 배치하면 두 문자열을 이어붙여 새 문자열을 만들 수 있습니다. $string1=&qu

Win11의 새로운 기능 분석: Microsoft 계정 로그인을 건너뛰는 방법 Win11의 새로운 기능 분석: Microsoft 계정 로그인을 건너뛰는 방법 Mar 27, 2024 pm 05:24 PM

Win11의 새로운 기능 분석: Microsoft 계정 로그인을 건너뛰는 방법 Windows 11이 출시되면서 많은 사용자는 Windows 11이 더 편리하고 새로운 기능을 제공한다는 사실을 알게 되었습니다. 그러나 일부 사용자는 시스템을 Microsoft 계정에 연결하는 것을 좋아하지 않아 이 단계를 건너뛰기를 원할 수도 있습니다. 이 문서에서는 사용자가 Windows 11에서 Microsoft 계정 로그인을 건너뛰고 보다 개인적이고 자율적인 환경을 달성하는 데 도움이 되는 몇 가지 방법을 소개합니다. 먼저 일부 사용자가 Microsoft 계정에 로그인하기를 꺼리는 이유를 이해해 보겠습니다. 한편으로는 일부 사용자들은 다음과 같은 걱정을 합니다.

Go 언어 파일 이름 바꾸기 작업에 대한 전체 분석 Go 언어 파일 이름 바꾸기 작업에 대한 전체 분석 Apr 08, 2024 pm 03:30 PM

os.Rename 함수는 Go 언어에서 파일 이름을 바꾸는 데 사용됩니다. 구문은 funcRename(oldpath,newpathstring)error입니다. 이 함수는 oldpath로 지정된 파일의 이름을 newpath로 지정된 파일로 바꿉니다. 예를 들어 간단한 이름 바꾸기, 파일을 다른 디렉터리로 이동, 오류 처리 무시 등이 있습니다. 이름 바꾸기 기능은 원자성 작업을 수행하며 두 파일이 동일한 디렉터리에 있는 경우에만 디렉터리 항목을 업데이트할 수 있습니다. 볼륨 전체에서 또는 파일이 사용 중인 동안에는 이름 바꾸기가 실패할 수 있습니다.

함수 오버로딩 및 재작성에 대한 C++ 템플릿 전문화의 효과 함수 오버로딩 및 재작성에 대한 C++ 템플릿 전문화의 효과 Apr 20, 2024 am 09:09 AM

C++ 템플릿 전문화는 함수 오버로딩 및 재작성에 영향을 줍니다. 함수 오버로딩: 특수화된 버전은 특정 유형의 다양한 구현을 제공할 수 있으므로 컴파일러가 호출하도록 선택하는 함수에 영향을 줍니다. 함수 재정의: 파생 클래스의 특수 버전은 기본 클래스의 템플릿 함수를 재정의하여 함수를 호출할 때 파생 클래스 개체의 동작에 영향을 줍니다.

C++를 사용하여 HTTP 스트리밍을 구현하는 방법은 무엇입니까? C++를 사용하여 HTTP 스트리밍을 구현하는 방법은 무엇입니까? May 31, 2024 am 11:06 AM

C++에서 HTTP 스트리밍을 구현하는 방법은 무엇입니까? Boost.Asio 및 asiohttps 클라이언트 라이브러리를 사용하여 SSL 스트림 소켓을 생성합니다. 서버에 연결하고 HTTP 요청을 보냅니다. HTTP 응답 헤더를 수신하고 인쇄합니다. HTTP 응답 본문을 수신하여 인쇄합니다.

phpcms는 어떤 프레임워크인가요? phpcms는 어떤 프레임워크인가요? Apr 20, 2024 pm 10:51 PM

PHP CMS는 웹 사이트 콘텐츠 관리를 위한 PHP 기반 오픈 소스 콘텐츠 관리 시스템으로, 사용 편의성, 강력한 기능, 확장성, 높은 보안 및 무료 오픈 소스가 특징입니다. 시간을 절약하고, 웹사이트 품질을 향상시키며, 협업을 강화하고, 개발 비용을 절감할 수 있으며, 뉴스 웹사이트, 블로그, 기업 웹사이트, 전자상거래 웹사이트, 커뮤니티 포럼 등 다양한 웹사이트에서 널리 사용되고 있습니다.

WeChat 로그인 통합 가이드: PHPCMS 실전 전투 WeChat 로그인 통합 가이드: PHPCMS 실전 전투 Mar 29, 2024 am 09:18 AM

제목: WeChat 로그인 통합 가이드: PHPCMS의 활용 오늘날 인터넷 시대에 소셜 로그인은 웹사이트의 필수 기능 중 하나가 되었습니다. 중국에서 가장 인기 있는 소셜 플랫폼 중 하나인 WeChat의 로그인 기능은 점점 더 많은 웹사이트에서도 사용되고 있습니다. 이 기사에서는 WeChat 로그인 기능을 PHPCMS 웹사이트에 통합하는 방법을 소개하고 구체적인 코드 예제를 제공합니다. 1단계: WeChat Open Platform 계정 등록 먼저 WeChat Open Platform에 개발자 계정을 등록하고 해당 개발 권한을 신청해야 합니다. 로그인 [위챗 오픈 플랫폼]

See all articles