⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 documentation-4.html

📁 PHPLOB注释详细版 使用模板技术的好帮手 PHP最有用的东东了
💻 HTML
📖 第 1 页 / 共 2 页
字号:
<HR></CODE></BLOCKQUOTE></LI></UL><P>Now you have a <CODE>$cart</CODE> object available by default on everypage that uses PHPLIB. That object is created automatically atsession startup, is carried from page to page by PHPLIBs sessionmanagement and is destroyed by the garbage collection that reapssession records. You do not have to worry anymore about thatcart, but simply use it anytime between <CODE>page_open()</CODE>and <CODE>page_close()</CODE>. PHPLIB does the rest for you.<P>The <CODE>Cart</CODE> class is actually dead stupid. It maintains an array<CODE>$cart-&gt;item[]</CODE> that holds records about what the user bought. Each<CODE>$cart-&gt;item[$x]</CODE> consists of a<CODE>$cart-&gt;item[$x]["art"]</CODE>, which isthe article number of an item the user wants to buy and of a<CODE>$cart-&gt;item[$x]["num"]</CODE>, which is the # of items with that articlenumber that are wanted. <CODE>$cart-&gt;currentItem</CODE> is the next $x to usefor articles added to <CODE>$cart-&gt;item[]</CODE>.<P>You add articles to the shopping cart with<P><BLOCKQUOTE><CODE><HR><PRE>$x = $cart->add_item($art, $num)</PRE><HR></CODE></BLOCKQUOTE><P>This will add <CODE>$num</CODE> items with the article number <CODE>$art</CODE>to your cart contents. If you already have an item with thatarticle number in your cart, the count for that article isincreased by <CODE>$num</CODE>. Otherwise a new article entry is beingcreated and set to <CODE>$num</CODE>. The function does return the<CODE>$x</CODE> index into the <CODE>$cart-&gt;item[]</CODE> array for that article.<P>To remove an item from the shopping cart, code<P><BLOCKQUOTE><CODE><HR><PRE>$x = $cart->remove_item($art, $num)</PRE><HR></CODE></BLOCKQUOTE><P>This will remove <CODE>$num</CODE> items with the article number<CODE>$art</CODE> from your cart, if there are that many items in yourshopping cart. If you do not have the <CODE>$art</CODE> in your cart orthere are not <CODE>$num</CODE> many <CODE>$art</CODE> in your cart, thefunction will return false and not remove anything from thecart. Otherwise, <CODE>$num</CODE> articles with article number<CODE>$art</CODE> are taken out of the cart and if the count for thatarticle drops to zero while doing this, we even unset the arrayelement.<P>You may check how many articles with a given article number arein the cart:<P><BLOCKQUOTE><CODE><HR><PRE>list($have, $num) = $cart->check($art)</PRE><HR></CODE></BLOCKQUOTE><P>The check function does return a two-element array. The firstelement <CODE>$have</CODE> is true, if we have the wanted article in the cart.If <CODE>$have</CODE> is true, <CODE>$num</CODE> holds the number of articles with thatnumber in the cart, otherwise <CODE>$num</CODE> is undefined (actually, it is0, but you must not rely on that).<P>Finally, we have a function<P><BLOCKQUOTE><CODE><HR><PRE>$cart->show_all()</PRE><HR></CODE></BLOCKQUOTE><P>which you may call to walk your shopping cart and haveExample_Cart to generate a list of articles in your cart. Thatfunction will first call <CODE>$cart-&gt;show_cart_open()</CODE>, for which youmay provide code in your subclass. It will then call<CODE>$cart-&gt;show_item($art, $num)</CODE> for each item in the cart. We have astupid default implementation for that function in Cart, but youmay provide more sophisticated code in <CODE>Example_Cart</CODE> for that, too.Finally, at the end of your cart listing,<CODE>$cart-&gt;show_cart_close()</CODE> is being called, which again may be codeof yours.<P>The example in the previous section shows a moresophisticated implementation of a Cart subclass. Thatimplementation uses show_cart_open() to create an opening table tag (formatted with a CSS class) and sets a counter<CODE>$cart-&gt;sum</CODE> tozero.<P>In show_cart_close(), the table is being closed and the<CODE>$cart-&gt;sum</CODE> counter is printed.<P>As you might have guessed, <CODE>show_item($art, $num)</CODE> queries thedatabase for each article number, retrieves the articledescription and prices and finally sums up all prices, taking thenumber of articles per article into consideration. It alsogenerates table rows, printing a nice receipt for the customer.<H2><A NAME="ss4.2">4.2 Template</A></H2><P><EM>Note:</EM> If you think that this is like FastTemplates, readcarefully. It isn't.<P><P> The template class allows you to keep your HTML code in someexternal files which are completely free of PHP code, butcontain replacement fields. The class provides you withfunctions which can fill in the replacement fields witharbitrary strings. These strings can become very large, e.g.entire tables.<P><P><H3>Instance variables</H3><P><P><CENTER><TABLE BORDER><TR><TD><BR>classname</TD><TD>String. Serialization helper: The name of this class.</TD></TR><TR><TD>debug</TD><TD>Boolean: if set to true, the class will emitdebugging output.</TD></TR><TR><TD>unknowns</TD><TD>One of "keep", "comment", "remove" (Default).Determines how to handle unresolved variable names intemplates upon output. If set to "keep", those are leftuntouched. If set to "comment", unresolved variable names aretransformed into HTML comments reporting the error. If set to"remove", unresolved variable names are silently removed (thedefault).</TD></TR><TR><TD>halt_on_error = "yes"</TD><TD>One of "yes"(Default), "report", "no". Determines how Template handleserror conditions. If set to "yes" (the Default), the error isreported, then execution is halted. If set to "report", theerror is reported, then execution continues by returning"false". If set to "no", errors are silently ignored, andexecution resumes reporting "false".</TD></TR><TR><TD>last_error = ""</TD><TD>The last error message iskept in this variable.</TD></TR><TR><TD><CAPTION>Accessible instance variables.</CAPTION></TD></TR></TABLE></CENTER><P><CENTER><TABLE BORDER><TR><TD><BR>file</TD><TD>Hash of strings. A translation table whichtranslates variable names into filenames.</TD></TR><TR><TD>root</TD><TD>String (Pathname). The base directory from whichtemplate files are being loaded.</TD></TR><TR><TD>varkeys</TD><TD>Hash of strings. A translation table whichtranslates variable names into regular expressions forthemselves.</TD></TR><TR><TD>varvals</TD><TD>Hash of strings. A translation table whichtranslates variable names into replacement values for theirrespective varkeys.</TD></TR><TR><TD><CAPTION>Internal instance variables.</CAPTION></TD></TR></TABLE></CENTER><P><H3>Instance methods</H3><P><P><H3>Accessible instance methods</H3><P><P><DL><DT><B>Template($root = ".", $unknowns = "remove")</B><DD><P>Constructor. May be called with two optional parameters. Thefirst parameter sets the template directory (see<CODE>set_root()</CODE>, the second parameter sets the policyregarding handling of unknown variables.<P><DT><B>set_root($root)</B><DD><P>The function checks that $root is a valid directory and setsthis directory as the base directory where templates are beingstored.<P><DT><B>set_unknowns($unknowns = "keep")</B><DD><P>The function sets the policy for dealing with unresolvedvariable names. Must be either "remove", "comment" or "keep". Ifset to "keep", those are left untouched. If set to "comment",unresolved variable names are transformed into HTML commentsreporting the error. If set to "remove", unresolved variablenames are silently removed (the default).<P><DT><B>set_file($handle, $filename = "")</B><DD><P>The function defines a filename for the initial value of avariable. It may be called with either a $handle/$filename pairor with a hash of $handle/$filename pairs. The files are notreferenced yet, but only when needed.<P><DT><B>set_block($parent, $handle, $name = "")</B><DD><P>A variable $parent may contain a variable block named by$handle. The function removes that block from $parent andreplaces it with a variable reference named $name. If $name isomitted, it is assumed to be the same as $handle.<P><DT><B>set_var($varname, $value = "")</B><DD><P>The functions sets the inital value of a variable. It may becalled with either a $varname/$value pair or with a hash of$varname/$value pairs.<P><DT><B>subst($handle)</B><DD><P>The function returns the value of the variable named $handle,with all defined variable values filled in. The resulting stringis not "finished", that is, the unresolved variable name policyhas not been applied yet.<P><DT><B>psubst($handle)</B><DD><P>This is a shorthand for <CODE>print $this->subst($handle)</CODE>.<P><DT><B>parse($target, $handle, $append = false)</B><DD><P>The function substitutes the values of all defined variables inthe variable named $handle and stores or appends the result inthe variable named $target.<P>If $handle is an array of variable names, $append is ignored.The variables named by $handle are being sequentiallysubstituted and the result of each substitution step is storedin $target. The resulting substitution is available in thevariable named by $target, as is each intermediate step for thenext $handle in sequence.<P><DT><B>pparse($target, $handle, $append = false)</B><DD><P>A shorthand for <CODE>print $this->parse(...)</CODE>.<P><DT><B>get_vars()</B><DD><P>Returns a hash of all defined values, keyed by their names.<P><DT><B>get_var($varname)</B><DD><P>Returns the value of the variable named by $varname. If $varnamereferences a file and that file has not been loaded, yet, thevariable will be reported as empty.<P>When called with an array of variable names, an hash of values,keyed by their names, will be returned.<P><DT><B>get_undefined($handle)</B><DD><P>The function will return a hash of unresolved variable names in$handle, keyed by their names (that is, the hash has the form$a[$name] = $name).<P><DT><B>finish($str)</B><DD><P>The function will returned the finished version of $str, thatis, the policy regarding unresolved variable names will beapplied to $str.<P><DT><B>p($varname)</B><DD><P>The function will print the finished version of the value of thevariable named by $varname.<P><DT><B>get($varname)</B><DD><P>The function will return the finished version of the value ofthe variable named by $varname.<P><DT><B>haltmsg($msg)</B><DD><P>This function can be overridden by your subclass of Template. Itwill be called with an error message to print.</DL><P><H3>Internal instance methods</H3><P><DL><DT><B>filename($filename)</B><DD><P>When called with a relative pathname, this function will returnthe pathname with $this->root prepended. Absolute pathnames aretaken unchanged.<P>The resulting filename must exist, or an error is generated.<P><DT><B>varname($varname)</B><DD><P>The function will construct a variable name regexp for a givenvariable name.<P><DT><B>loadfile($handle)</B><DD><P>If a variable is undefined or empty and is backed by a filename,the backing file will be loaded and the files contents will beassigned as the variables value.<P><DT><B>halt($msg)</B><DD><P>This function is called whenever an error occurs and will handlethe error according to the policy defined in$this->halt_on_error.</DL><P><H3>Example</H3><P>The class manages a set of variables which are text strings.These strings may contain references to other variables in theform of "{variable}". When parsed or substituted, a variablereference is being replaced by the value of that variable.<P>A variable value may be defined manually by calling<CODE>set_var("name", "value");</CODE> or it may be defined froma file by calling <CODE>set_file("name","filename.ihtml");</CODE>. In the latter case, the contents of thefile are being loaded when needed (as late as possible) and setas the value of that variable.<P>A third way to define a variable value is to call<CODE>set_block("parent", "block", "name");</CODE>. In this case,the variable named <CODE>parent</CODE> is being searched for a blockthat starts with <CODE>&lt;!-- BEGIN block --&gt;</CODE> and endswith <CODE>&lt;!-- END block --&gt;</CODE>. This string is removedfrom the variable <CODE>parent</CODE> and assigned to the variable named<CODE>block</CODE>. In <CODE>parent</CODE>, a variable reference to <CODE>name</CODE> isplaced instead. If the optional parameter <CODE>"name"</CODE> is leftout, <CODE>"block"</CODE> is being used instead.<P>Use <CODE>Template</CODE> direcly or define a subclass of <CODE>Template</CODE>as needed.<P>Define a template file named page.ihtml as follows:<P><BLOCKQUOTE><CODE><HR><PRE>&lt;html&gt; &lt;head&gt;&lt;title&gt;{PAGETITLE}&lt;/title&gt;&lt;/head&gt; &lt;body bgcolor="#ffffff"&gt; &lt;table border=1 cellpadding=4 cellspacing=0 bgcolor="#eeeeee"&gt;  &lt;tr&gt;   &lt;td colspan=2&gt;&lt;h1&gt;{PAGETITLE}&lt;/h1&gt;&lt;/td&gt;  &lt;/tr&gt;  &lt;tr&gt;   &lt;td&gt;{OUT}&lt;/td&gt;   &lt;td&gt;Content&lt;/td&gt;  &lt;/tr&gt; &lt;/table&gt; &lt;/body&gt;&lt;/html&gt;</PRE><HR></CODE></BLOCKQUOTE><P>This file contains a reference to the variable <CODE>pagetitle</CODE>and a reference to the variable named <CODE>out</CODE>. Another template file, named box.ihtml, contains a block named row with threevariable references {TITLE}, {NUM} and {BIGNUM}:<P><BLOCKQUOTE><CODE><HR><PRE>&lt;!-- start box.ihtml --&gt;&lt;table border=1 bgcolor="#cccccc" cellpadding=4 cellspacing=0&gt; &lt;tr&gt;  &lt;td colspan=2&gt;&lt;b&gt;{TITLE}&lt;/b&gt;&lt;/td&gt; &lt;/tr&gt;  &lt;!-- BEGIN row --&gt;  &lt;tr&gt;   &lt;td&gt;{NUM}&lt;/td&gt;   &lt;td&gt;{BIGNUM}  &lt;/tr&gt;  &lt;!-- END row --&gt;&lt;/table&gt;&lt;!-- end box.ihtml --&gt;</PRE><HR></CODE></BLOCKQUOTE><P>The following php3 file demonstrates how to use these templates:<P><BLOCKQUOTE><CODE><HR><PRE>&lt;?php  include("./template.inc");  # create Template instance called $t    $t = new Template("/page/to/webserver/template", "keep");  # define variables named page and box, referencing files  $t-&gt;set_file(array(     "page" =&gt; "page.ihtml",     "box"  =&gt; "box.ihtml"));  # extract the block named "row" from "box", creating a  # reference to {rows} in "box".  $t-&gt;set_block("box", "row", "rows");  # define the variables TITLE and PAGETITLE  $t-&gt;set_var(array("TITLE"     =&gt; "Testpage",                    "PAGETITLE" =&gt; "hugo"));  # define NUM and BIGNUM, then append "row" to "rows"...  for ($i=1; $i&lt;=3; $i++) {    $n  = $i;    $nn = $i*10;    $t-&gt;set_var(array("NUM" =&gt; $n, "BIGNUM" =&gt; $nn));    $t-&gt;parse("rows", "row", true);  }  # build out from box, then build out from page...  $t-&gt;parse("out", array("box", "page"));  # finish out and print it.  $t-&gt;p("out");?&gt;&lt;hr&gt;&lt;?php  # report leftover variables, if any.  print implode(", ", $t-&gt;get_undefined("rows")); ?&gt;</PRE><HR></CODE></BLOCKQUOTE><P><P><HR><A HREF="documentation-5.html">Next</A><A HREF="documentation-3.html">Previous</A><A HREF="documentation.html#toc4">Contents</A></BODY></HTML>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -