nutballs

Per my

learn

 ing 

PHP

  thread, I have adapted my templating system I use in

ASP

 .

This has resulted in a few questions, so here goes.
I do a bunch of

regex

  replacements for tokens that are more complicated than just a single replacement. such as #PASTARTICLES-5# which would display 5 articles. I just don't have one of those implemented yet. Those are straightforward, however, the question comes into play for the Other tokens. Specifically my CONTENT token.

In the code page I put a function called content, shown below. That content function is a wrapper for HTML of the content area. That HTML generally might have code snips inserted, such as echo time(); for example. Is there any issue with the way I am mode switching from

PHP

  to HTML so much? In

ASP

  its pretty much a non-issue, if you do it right.

Also, splitting the template on all the # symbols is an easy way to deal with all the left over tokens. But as the template gets to a real one, currently it isn't, does splitting a dozen tokens, with such huge variances in resulting array node sizes an issue? i'm assuming not, but I gotta make sure.

errr there was something else, but my brain just pooped out, time for bed.

----------------------------
CODE Snippits:

The template processor function which is included in all pages.

function dotemplate($whichtemplate)
{
$filepath = TEMPLATEPATH.$whichtemplate;
$templatefile = fopen($filepath, 'r');
$template = fread($templatefile, filesize($filepath));
fclose($templatefile);

//do

REGEX

  replacements
        //none yet

//do Split replacements for HTMLfunctions Must be after any egex stuff
//since

regex

  replacement change the value of $template and this section does the writing out.
$templateArr = explode("#",$template);
foreach ($templateArr as $chunk)
{
switch ($chunk)
{
case "CONTENT" : content();
break;
case "METATITLE" : echo $GLOBALS['metatitle'];
break;
case "MESSAGE" : ShowMsg();
break;
default : echo $chunk;
}
}
}


The Template:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
<title>#METATITLE#</title>
<link href="/styles.css" rel="stylesheet" type="text/css" />
</head>
<body>
#MESSAGE#<br />
#CONTENT#
</body>
</html>


The Content Function which sits in my actual page:

<?

php

  function content() { //START CONTENT HTML============================================= ?>

ManyDo Home<br />
The time is <?

php

  echo time(); ?><br />

<?

php

  } //END CONTENT HTML================================================================== ?>

perkiset

quote author=nutballs link=topic=519.msg3347#msg3347 date=1190271961

I do a bunch of

regex

  replacements for tokens that are more complicated than just a single replacement. such as #PASTARTICLES-5# which would display 5 articles. I just don't have one of those implemented yet. Those are straightforward, however, the question comes into play for the Other tokens. Specifically my CONTENT token.

I have some suggested code at the bottom of this post... I've been hinting at it, but will make it clear now.


quote author=nutballs link=topic=519.msg3347#msg3347 date=1190271961

In the code page I put a function called content, shown below. That content function is a wrapper for HTML of the content area. That HTML generally might have code snips inserted, such as echo time(); for example. Is there any issue with the way I am mode switching from

PHP

  to HTML so much? In

ASP

  its pretty much a non-issue, if you do it right.

It is a non-issue, however it is not seen as particularly good form. Personally, I prefer a pure form of

PHP

  with specific outputs as opposed to starting and stopping the code the way that you have it. Here's two examples of what I mean - the first, a way that many folks do it but I personally do not approve of, and the second, the way that I do it:


<html>
<body>
<H1>Hello - the date is <?

php

  echo date('m/d/y', time()); ?></H1>
</HTML>



<?

php

 

$t = date('m/d/y', time();

echo <<<HTML
<html>
<body>
<H1>Hello - the date is $t</H1>
</HTML>
HTML;

?>


Although the difference is ever-so-slight (and output time would probably be identical) for <me>, it is important to get into a language and stay there. It's easier for me to think of blocks of HTML that I am outputting when I choose to within a script, then it is an HTML page where I am interspersing code. I also believe that this makes my down-the-road readability considerably better.


quote author=nutballs link=topic=519.msg3347#msg3347 date=1190271961

Also, splitting the template on all the # symbols is an easy way to deal with all the left over tokens. But as the template gets to a real one, currently it isn't, does splitting a dozen tokens, with such huge variances in resulting array node sizes an issue? i'm assuming not, but I gotta make sure.

OK, code example. Essentially, you want to put items with parameters into your output text. Please consider the following... NOTE that this is not necessarily the best all-around way to do it, but I want to spin your gears here with a different (and more

PHP

  way) of thinking. This example contains 3 separate files: class.nutballs.

php

 , which is a content generation class, template.

php

  which is your website template file and index.

php

  which is the actual file that the surfer requested.

First, the index.

php

  file - this is what the surfer called for:

<?

php

 

$path = '/www/sites/nb';
require_once("$path/class.nutballs.

php

 ");

$nb = new nutballsOutputComponent();
$nb->titleBase = 'The Really Big Site';
$nb->message = file_get_contents("$path/messageFile.txt");
$nb->content = file_get_contents("$path/contentFile.txt");

// Here's the magic:
require_once("$path/output.

php

 ");

?>



Now, the class.nutballs.

php

  file:

<?

php

 

class nutballsOutputComponents()
{
public $titleBase;
public $message;
public $content;

function title()
{
// A function to return the title base with the requested URI...
return "{$this->titleBase}: {$_SERVER['REQUEST_URI']}";
}
function searchResults($theCount)
{
// ... Code to output($theCount) number of search results...
}

function shoppingCart()
{
// ... Code to display the shopping cart...
}
function showMRU($theCount)
{
// ... Code to output($theCount) lines from a most-recently-used list
}
}



Finally, here is the template.

php

  file:

<?

php

 

echo <<<BLOCK
<html>
<head>
<title>{$nb->title()}</title>
</head>
<body>

{$nb->searchResults(10)}

<br><br><br>

{$nb->shoppingCart()}

<br><br><br>

{$nb->showMRU(5)}
{$nb->message}<br>
{$nb->content}<br>

</html>
BLOCK;

?>


I've done much the same as you - separated the content from the processor from the request... but in this way, we're using some of the best features of

PHP

 . The most important here is the single-pass processing of the actual content in template.

php

 , using object references within a text block - rather than parsing out and recombining the text, the single-pass processing will call the executable code where it finds it in the block. As you can see, there is no parsing in this routine at all. In a way,

PHP

  is kind of doing what your code does, but at C speed and in a single pass rather than you having to process it. Additionally, it makes the separation of church and state really clear... the executable stuff is <here> while the content is <there>.

And as you can see, by separating that mess from the actual request, the index.

php

  file could very easily grab any template file and use it - it does not care what the output is at all... and the output template does not care at all what the content processor is doing.

Obviously you could WAY increase the capabilities of the nutballsOutputComponent - give it properties for paths, have it understand how to get its own content, you name it - I just made it be simple and readable here.

Some might argue that the template.

php

  file should actually fill a variable and then the index.

php

  file should print/echo it... that's true, that is much more "one-in-one-out" thinking... I just wanted to show some different notions of ways that things can be spit back out.

I dunno - perhaps I'm just too objecty, but this kind of thinking makes way more sense to me.

/p

nutballs

follow up from the phone conversation.

I get it. For anyone else trying to play along, perk is doing the exact same thing. But his way is much better. Since with his method it all stays in the compiled code, as opposed to my way, which loads a file from disk. In

ASP

  this was not an issue really, because the file would get cashed and there is a slight difference in how they get included that I take advantage of.

At first I was thinking that his way was more complicated, since you have to create a class with methods for each "TOKEN", however, it is the same exact thing I am doing. All i had to do was realize that he is using tokens as well, just they happen to be object.method calls. From a designer management point of view, it is almost the same. Though I can foresee a very stupid conversation at some point of "what is that <?

php

  echo <<<CONTENT thingy? You cant put anything before the doctype!!!" My response unfortunately will have to be a dickish "i'm smarter than you, just accept it."

I also didnt think that nesting would work either, but it would, perfectly.

example is a site with a main template for the interface, header, footer, navs, etc, all in one template file.
then the content area is supported by other templates, that can get included just like the main template, {$templateobject->contentarea} which would then include the appropriate template for what page they are on. Or, i can just have that content area in the page the user is on. like i did in my example above.

now to convert my

learn

 ing  project to this...

nutballs

Alright so Im trying to convert over to this and I get an error on my classApplause

Parse error: parse error, unexpected '(', expecting '{' in /_classes.

php

  on line 3


<?

php

 

class template()  //<----this is line 3
{
public $metat; //the meta title of the page
public $metak; //the meta keywords of the page
public $metad; //the meta description of the page
public $templatefile; //the filename only of the template file to use for the page.

public function filepath()
{
return $this->templatefile;
}

public function title()
{
return $this->metat;
}

public function keywords()
{
return $this->metak;
}

public function description()
{
return $this->metad;
}

public function messages()
{
return ShowMsg();
}

public function content()
{
return pagecontent();
}
}

?>

perkiset

No parens on the class name:

class template
{
}

or

class template extends anotherClass

nutballs

but then I get:

Parse error: parse error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or '}' in /_classes.

php

  on line 5

perkiset

also, you don't need functions to return those vars... this is fine:

class myClass
{
public $aVar;
function aFunc() { return 'Hello World'; }
}

$c = new myClass();
$var = <<<TEXT
This is a test: {$c->aVar} or {$c->aFunc()}
TEXT;

perkiset

quote author=nutballs link=topic=519.msg3360#msg3360 date=1190333778

but then I get:

Parse error: parse error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or '}' in /_classes.

php

  on line 5


What version of

PHP

 ? "public" did not exist until 5.0...

if its < 5.0 then just put the var name in the class thus:

class template
{
var $myVar;
}

You don't even really need to declare them - it's just nice for later readability

nutballs

ah thats why.

php

 4.

hmm. i like being strict about my declarations. I will have to move to another provider at some point then I guess.

uh, wait. you mean i could have a class

class someclass
{
//nothing in here.
}


And then from code I could declare vars that dont yet exist?!?!
$someclass->nonexistantvar = 'test';

is that right? if so, thats retarded. no
typo
  protection... is there like a strict command or something that will force all vars to require declaration?

perkiset

quote author=nutballs link=topic=519.msg3363#msg3363 date=1190334300

uh, wait. you mean i could have a class

class someclass
{
//nothing in here.
}


And then from code I could declare vars that dont yet exist?!?!
$someclass->nonexistantvar = 'test';

is that right? if so, thats retarded. no
typo
  protection... is there like a strict command or something that will force all vars to require declaration?


Applause retarded indeed, yet true. Functions no, vars yes. And no, there's no strict mode. You have to implement that yourself using __get and __set (see the Nutballs

learn

 ing  thread for more on the magic methods) so it can be done, but not by default. And of course, forget a capitalization and you're equally screwed. It's essentially the same as normal old variables and array references - you can set and use without them actually existing. Took me a while to forgive them for that one Applause

I recommend setting error_reporting(E_ALL) at the top of your scripts for a while to see if you're in compliance with all your var names.

perkiset

And btw, I'm right with you - I am MR STRICT when it comes to this stuff because it's the only way that I can re-read my code 6 months later. Fortunately, I'm such a structurenazi that it's pretty easy for me *not* to screw up.

...but it has been known to happen :Applause

nutballs

wow, that is deranged, but it makes sense with the looseygoosey var handling in

php

 .

BTW, i can run

PHP

 5, and just turned it on.

you set a rule in the .htaccess file (at least at 1and1 shared

linux

  hosting)
AddType x-mapp-

php

 5 .

php

 

perkiset

Sweet... MUCH better. 5.0 or 5.2? 5.1 was a Charlie Foxtrot...

nutballs

5.2.1 it seems.

at least now I can set the visibility of class methods and such. that actually put me off a bit.

nutballs

Just an update. I converted my project over to using your template methodology, with some slight tweaks to my style. Thanks again. this is a better way definitely since I am eliminating the parsing steps from the process, plus because I can drop functions strait into the HTML. The only thing I need to keep remembering is that the functions need to return the strings, not just ECHO from the function. better coding practice that way anyway, so good thing to force. I also

learn

 ed that you can do something similar to HEREDOC by using single quotes.

$somevar = '
<body>
some text<br/>
some text that now ap

pear

 s on a new line not only on page, but also in source.
</body>
';

that has turned out to be very useful, so I don't have to CLASS everything I ever want to put in-page.

perkiset

Oh bigtime... the CLASS trick is to snuggle code into a text block... if you can avoid it with what you just posted that's WAY better since it's static strings in the code... *hugely* faster and cleaner.

Fishsticks.... best watch my as you'll be a better

PHP

 ster than me in no time

nutballs

doubtful... lol

i still don't really get the difference between ' and "

but im sure at some point it will click.

perkiset

It's really about how they are handled at the C level.

If you say $myVar = 'This is a test';
echo $myvar

the compiler will literally take the bytes in memory local $myVar and dump them out as is.

If you say
$myVar = "This is a test";
echo $myvar

the compiler will run the string throug a different piece of code, looking for variables along the way. It's kind of

regex

 ing the string for variable references and if there are none, it does nothing - but if there are some, it inclused them in the serial output of the string.

The difference is that when you output a ' ... ' string there is no processing associated with it - it is as fast as

PHP

  can go. If you output a " --- " string then you add a little time because

PHP

  has to ascertain if there are any references in the string to variable/array/object or not before it outputs it.

Clearly, if you have a two string page then this is a meaningless distinction... but if you're doing a lot of string handling it's simply inefficient to wrap everything in " -- " - best tool for the job and all, IMO. And I personally use the distinction almost like I use variable names - helps me remember what I was doing with the string at the time when I wrote the code. If I see '... without even scanning across the string I know there's nothing (no *code per se*) going on in that string.

/p


Perkiset's Place Home   Politics @ Perkiset's