2011-10-05 132 views
1

我試圖創建一個網站,允許像WordPress和其他CMS系統一樣簡單的主題添加/操作。要做到這一點,我想使它成爲可以傳遞內容的主題文件儘可能少的php代碼。目前,這是(極其簡單)班有一個PHP類返回數組值,並保持循環,直到結束

class getparents { 
     var $parentsarray; 

    function get_parents() { 
       $this->parentsarray = array(); 
       $this->parentsarray[] = array('Parent0',3,1); 
       $this->parentsarray[] = array('Parent1',8,2); 
       $this->parentsarray[] = array('Parent2',2,3); 
       return $this->parentsarray; 
     } 
} 

和檢索它像這樣:

$parents = new getparents(); 

?><table><?php 
foreach($parents->get_parents() as $rowtable) 
{ 
    echo "<tr><td>$rowtable[0] has category ID $rowtable[1] and is on level $rowtable[2] </td></tr>"; 
} 
?></table><?php 

但我想使檢索更是這樣的:

<table> 
    <tr><td><?php echo $cat_title; ?> has category ID <?php echo $cat_id; ?> and is on level <?php echo $cat_level; ?> </td></tr> 
</table> 

哪基本上意味着類將以一種可以理解的方式返回值並自動繼續循環,而不需要用戶添加* foreach($ parents-> get_parents()作爲$ rowtable)*或類似的東西主題文件。

下面是一個例子wordpress頁面(希望)來說明我的意思。此頁面檢索當前wordpress類別的所有帖子,這是我試圖在腳本中模仿的內容,但不是檢索帖子,而是檢索該類別的父母,但我認爲解釋該問題並不重要。

<?php 
/** 
* The template for displaying Category Archive pages. 
* 
* @package WordPress 
* @subpackage Twenty_Ten 
* @since Twenty Ten 1.0 
*/ 

get_header(); ?> 

     <div id="container"> 
      <div id="content" role="main"> 

       <h1 class="page-title"><?php 
        printf(__('Category Archives: %s', 'twentyten'), '<span>' . single_cat_title('', false) . '</span>'); 
       ?></h1> 
       <?php 
        $category_description = category_description(); 
        if (! empty($category_description)) 
         echo '<div class="archive-meta">' . $category_description . '</div>'; 

       /* Run the loop for the category page to output the posts. 
       * If you want to overload this in a child theme then include a file 
       * called loop-category.php and that will be used instead. 
       */ 
       get_template_part('loop', 'category'); 
       ?> 

      </div><!-- #content --> 
     </div><!-- #container --> 

<?php get_sidebar(); ?> 
<?php get_footer(); ?> 

注意:我的實際問題與wordpress沒有任何關係,所以我沒有將它作爲標籤添加。

更新:我想我的問題可能不清楚。下面是一個混亂的例子(即工作仍然)

的index.php

<?php 
include_once("class.php"); 
include_once("config.php"); 
if(isset($_GET['catid'])) 
{ 
    $getproducts = new getproducts($_GET['catid']); 
    $catproductsarray = $getproducts->getarray(); 

    $indexxx = 0; 
    foreach($catproductsarray as $rowtable) 
    { 
     include("templates/$template/all_products.php"); 
     $indexxx++; 
    } 
} 

class.php

class getproducts { 

    var $thearrayset = array(); 

    public function __construct($indexx) { 
    $this->thearrayset = $this->makearray($indexx); 
    } 

    public function get_id($indexxx) { 
    echo $this->thearrayset[$indexxx]['id']; 
    } 

    public function get_catID($indexxx) { 
    echo $this->thearrayset[$indexxx]['catID']; 
    } 

    public function get_product($indexxx) { 
    echo $this->thearrayset[$indexxx]['name']; 
    } 

    public function makearray($indexx) { 
    $thearray = array(); 
     if(!is_numeric($indexx)){ die("That's not a number, catid."); }; 
     $resulttable = mysql_query("SELECT * FROM products WHERE catID=$indexx"); 
     while($rowtable = mysql_fetch_array($resulttable)){ 
      $thearray[] = $rowtable; 
     } 

    return $thearray; 
    } 

    public function getarray() { 
    return $this->thearrayset; 
    } 

} 

模板/默認/ all_products.php

<!-- The below code will repeat itself for every product found --> 
<table> 
<tr><td><?php $getproducts->get_id($indexxx); ?> </td><td> <?php $getproducts->get_catID($indexxx); ?> </td><td> <?php $getproducts->get_product($indexxx); ?> </td></tr> 
</table> 

所以基本上, index.php被用戶加載,之後mysql數據庫中的產品數量將從該類中提取。對於每個產品,all_products.php都會以$ indexxx加1來調用。

現在用戶唯一需要做的就是編輯HTML all_products.php,產品將全部以不同的方式顯示。這就是我要做的,但是要以一種乾淨,負責任的方式。不是這樣,這是一團糟!

UPDATE2:我找到了一個更好的方法來做到這一點,但添加它作爲答案。看起來更合適,並且將這個問題從已經比過去更久的地方變成現實。

+2

如果你在某種程度上強制某個特定的輸出(比如這組桌面原始數據,例如),你的主題根本就不易管理。你應該考慮使用像Smarty這樣的模板引擎,或者構建一個更簡單的定製引擎。如果你不想考慮php本身是一個模板引擎,當然 –

+0

@DamienPirsy我只是用它作爲例子。我遇到的問題是自動循環和php變量有意義,而不是返回整個數組,並使用$ arrayname [x]來回顯值。正如它在示例中所示,用戶可以選擇不使用表格,只需將<?php echo $ cat_title; ?>有類別ID <?php echo $ cat_id; ?>並且在級別<?php echo $ cat_level; ?>
這正是我希望他們能夠做到的。 – natli

回答

1

好的,我正在接近我想要的東西,所以我將其添加爲一個答案。

模板:

<?php include("templates/$template/header.php"); ?> 
<!-- [product][description][maxchars=##80##][append=##...##] --> 
<!-- [categories][parents][name][append= ->] --><!-- maxchars=false means dont cut description --> 
<!-- [categories][children][prepend=nothing] --><!-- prepend=nothing means no prepend --> 

    <div id="middle-left-section"> 
     <table> 
     {start-loop-categories-parents} 
     <tr><td><a href="<!-- [categories][parents][url] -->"><!-- [categories][parents][name] --></a></td><td> 
     {end-loop-categories-parents} 
     </table> 

     <table> 
     <tr><td><!-- [categories][current] --></tr></td> 
     {start-loop-categories} 
     <tr><td>&nbsp;<!-- [categories][children] --></td><td> 
     {end-loop-categories} 
     </table> 
    </div> 
    <div id="middle-right-section"> 
     <table id="hor-minimalist-a"> 
     <thead> 
     <th scope="col">&nbsp;</th> 
     <th scope="col">Name</th> 
     <th scope="col" width="200px">Description</th> 
     <th scope="col">Price</th> 
     </thead> 
     <tbody> 
     {start-loop-product} 
     <tr><td><img src="fotos/<!-- [product][thumb] -->"></img></td><td><!-- [product][name] --></td><td><!-- [product][description] --></td><td><!-- [product][price] --></td></tr> 
     {end-loop-product} 
     </tbody> 
     </table> 
    </div> 
    <div style="clear: both;"/> 
</div> 
<?php include("templates/$template/footer.php"); ?> 

類:

<?php 
/////////////////////////// 
//Includes and functions// 
///////////////////////// 
include_once("config.php"); 
include_once("includesandfunctions.php"); 

function get_between($input, $start, $end) 
{ 
    $substr = substr($input, strlen($start)+strpos($input, $start), (strlen($input) - strpos($input, $end))*(-1)); 
    return $substr; 
} 

function get_between_keepall($input, $start, $end) 
{ 
    $substr = substr($input, strlen($start)+strpos($input, $start), (strlen($input) - strpos($input, $end))*(-1)); 
    return $start.$substr.$end; 
} 

class listproducts { 

var $thearrayset = array(); 
var $file; 
var $fp; 
var $text; 
var $products; 
var $productskeepall; 
var $done; 
var $returnthisloopdone; 

    public function __construct() { 
    global $template; 
    //Get items from mysql database and put in array 
    $this->thearrayset = $this->makearray(); 
    //Read file 
    $this->file = "templates/$template/all_products.php"; 
    $this->fp = fopen($this->file,"r"); 
    $this->text = fread($this->fp,filesize($this->file)); 

    //Set other vars 
    $this->products = ''; 
    $this->productskeepall = ''; 
    $this->returnthisloopdone = ''; 
    $this->done = ''; //Start $done empty 

    } 

    public function makearray() { 
    $thearray = array(); 
     $resulttable = mysql_query("SELECT * FROM products"); 
     while($rowtable = mysql_fetch_array($resulttable)){ 
      $thearray[] = $rowtable; //All items from database to array 
     } 
    return $thearray; 
    } 

public function getthumb($indexxx) { 
     $resulttable = mysql_query("SELECT name FROM mainfoto where productID=$indexxx"); 
     while($rowtable = mysql_fetch_array($resulttable)){ 
      return $rowtable['name']; //Get picture filename that belongs to requested product ID 
     } 
    } 

    public function listproduct() 
    { 
    global $template; 

     $this->products = get_between($this->done,"{start-loop-product}","{end-loop-product}"); //Retrieve what's between starting brackets and ending brackets and cuts out the brackets 
     $this->productskeepall = get_between_keepall($this->done,"{start-loop-product}","{end-loop-product}"); //Retrieve what's between starting brackets and ending brackets and keeps the brackets intact 

     $this->returnthisloopdone = ''; //Make loop empty in case it's set elsewhere 
     for ($indexxx = 0; $indexxx <= count($this->thearrayset) - 1; $indexxx++) //Loop through items in array, for each item replace the HTML comments with the values in the array 
     { 
      $this->returnthis = $this->products; 

      $this->returnthis = str_replace("<!-- [product][thumb] -->", $this->getthumb($this->thearrayset[$indexxx]['id']), $this->returnthis); 
      $this->returnthis = str_replace("<!-- [product][catid] -->", $this->thearrayset[$indexxx]['catID'], $this->returnthis); 
      $this->returnthis = str_replace("<!-- [product][name] -->", $this->thearrayset[$indexxx]['name'], $this->returnthis); 

      preg_match('/(.*)\[product\]\[description\]\[maxchars=##(.*)##\]\[append=##(.*)##\](.*)/', $this->done, $matches); //Check if user wants to cut off description after a certain amount of characters and if we need to append something if we do (like 3 dots or something) 
      $maxchars = $matches[2]; 
      $appendeez = $matches[3]; 
      if($maxchars == 'false'){ $this->returnthis = str_replace("<!-- [product][description] -->", $this->thearrayset[$indexxx]['description'], $this->returnthis); 
      }else{ $this->returnthis = str_replace("<!-- [product][description] -->", substr($this->thearrayset[$indexxx]['description'],0,$maxchars).$appendeez, $this->returnthis); 
      } 

      $this->returnthis = str_replace("<!-- [product][price] -->", $this->thearrayset[$indexxx]['price'], $this->returnthis); 

      $this->returnthisloopdone .= $this->returnthis; //Append string_replaced products section for every item in array 
     } 

     $this->done = str_replace($this->productskeepall, $this->returnthisloopdone, $this->done); 

     //Write our complete page to a php file 
     $myFile = "templates/$template/cache/testfile.php"; 
     $fh = fopen($myFile, 'w') or die("can't open file"); 
     $stringData = $this->done; 
     fwrite($fh, $stringData); 
     fclose($fh); 

     return $myFile; //Return filename so we can include it in whatever page requests it. 
    } 

} //End class 

?> 

由網站訪問者,這將調用當前模板的ALL_PRODUCTS請求的PHP。php

include_once("class.php"); 

$listproducts = new listproducts(); 
include_once($listproducts->listproduct()); 

所以這真的是,只是string_replacing模板文件中的HTML註釋與我想要的PHP結果。如果它是一個循環,我單擊我想循環的html代碼 - >啓動一個空字符串變量 - >重複該HTML代碼,將每個循環附加到字符串變量 - >使用此字符串變量替換HTML註釋

然後將新建頁面寫入實際文件,然後將其包含在內。

我完全不熟悉OOP,所以這對我來說是相當複雜的東西。我想知道這是否是解決我的問題的好方法。而且,是否有可能防止爲每個頁面重寫整個班級?

作爲一個例子,如果我也想建立一個留言簿,我想重寫這個類,它可以接受傳入的變量並從那裏建立頁面,而不是預先設置很多限制它的東西到一個「任務」,如檢索產品。但在我進一步探討之前,我想知道這是否可行。