Every wondered about code formatting?

I have eclipse set to use x number of spaces for my tabs. I can just hit the tab for an individual line or a block of code and it tabs it by my preference settings.

From Eclipse the spaces actually behave in the WYSYWG editors, like those used by Sitepoints bbform configuration. The tabs, when posting code cause a disaster as all of them are seen as no space at all.

The trade-off, like you mentioned is larger code files to represent the many extra spaces.

Regards,
Steve

<snip/>

[QUOTE=Salathe;5128085I]
Then I apologise for any offense caused, if any: such things I tend to assume everyone working with PHP day-to-day has picked up and knows about. Forgetting that variables are available cross-includes still, even after you have said so, seems like something that wouldn’t simply be forgotten. Then again, maybe I put too much credit in your favour and should assume less of the skills and knowledge of those giving advice here.[/QUOTE]
I don’t work on PHP every-day, in fact about 8 years ago I did, however I had to take on less ‘hands-on’ day-to-day programming, did management, infrastructure design, implementing process, and building business with a few small PHP projects in-between . I recently sold my business, so I am getting back into it, but still a little rusty. That does not mean I don’t know how to provide help and have not seen/faced many of the problems involved in these threads, but I will always try to be graceful if I am wrong, and when warranted, willing to take my lumps too. I’ve also recently been reading a lot of the php.net documentation; I don’t just believe in enhancing skills through osmosis. People like you ensure that I want to be my best.

It is more likely that I never learned about cross-includes and they did not knowingly affect what I’ve done when including classes or files.

[OT]Let’s keep on-topic and keep discussion of other members out Please!
If you feel a post has been edited or removed unfairly, or now find the thread difficult to follow, my apologies.[/OT]

@deathshadow60; You know who nailed the problem with scope bleeding? You’re not going to like the answer, but … Twig!

In Twig only the variables that you supply as arguments are available, and no other. Even in the Twig include block you can tell it to only pass a subset of the variables at that point to the file you’re including.


{% include 'foo' with {'foo': 'bar'} only %}

You can’t even access any superglobals without passing them as parameters (which is a good thing in my opinion).

I know you strongly dislike Twig, but for those who’re interested in the problem and looking for a nice solution, this may be it :slight_smile:

Have you looked to see how they achieve this?

DeathShadow60, what are the things you don’t like about it, other than it is not needed because PHP is a perfectly acceptable templating technology itself?

Steve

I haven’t, but since it uses lexical parser, I guess it’s just a matter of unsetting all symbols except for the one(s) supplied.

Basically unsetting all other variables for the current scope. Where the scope has nothing to do with PHP’s scope, but with Twig’s lexer scope.

Well, as I mentioned before the only places I ever use includes are when including class files or templates.

Whenever I do it via templates, this is the function I use. Basic but useful. It’s within a ‘content’ class, static because it’s instance-independent.

	public static function loadTemplate($Module, $Name, array $Variables = array()){
		$File = "Framework/Modules/{$Module}/Templates/{$Name}.tpl";
		if(file_exists($File)){
			extract($Variables);
			ob_start();
			include $File;
			return ob_get_clean();
		}else{
			return "Template not found: {$Module}/{$Name}";
		}
	}

Simple, the values ARE still passed to TWIG, it just doesn’t use them in it’s string processing. That’s it – no magic. It’s basically a separate interpreter running atop PHP (an interpreter)… as such anything it doesn’t do to the strings it’s processing, isn’t in ‘scope’. It actually IS in scope inside TWIG, but because TWIG doesn’t make use of them in it’s engine, you can’t see them from inside the engine.

It’s like the variables in the code written in C for PHP, JAVA, JavaScript, or any other interpreted language (and for all the “bytecode compiler” and “virtual machine” raving, a VM is at best a JIT compiler, at worst an interpreter! Those of us who used pascal to make P-Code three decades ago at least admit this) – you can’t directly access any of those inside the language because the interpreter lacks any mechanism for passing them. Since I’m writing my own interpreted language right now, I’ve been getting a refresher on that subject!

Like we need a better reason? I mean, it’s for all intents and purposes an interpreter written in an interpreted language – SLOW be thy name! Though there are plenty of other reasons…

For starters, to me it’s uselessly cryptic for no good reason. Concise does NOT mean shorten everything into abbreviations and symbols; when it comes to being concise, it seems many folks out there concentrate too much on the ‘short’ half of the equation, while completely forgetting the other half – being CLEAR. {{ var|escape }} is NOT clear…

It also seems crafted for the folks who like to open and close php on every blasted line – which BTW is more work for the interpreter; naturally we want to make more work for an interpreter that’s running atop another interpreter. What can we call that? A herpaderpeter?

In a lot of ways, it strikes me as the same type of nonsense as the folks who try to write entire “applications” using nothing more than BASH scripts – which would make sense given the syntax seems similar. That’s not a good thing…

deathshadow60, the argument that “language within an a language” is inane. PHP is an interpreted language written in C. Why use PHP instead of C? C is compiled into ASM. Why don’t we all code in that? That’d fit nicely with your obsession with performance, too. If performance is that critical you shouldn’t be using PHP.

The point of abstraction–and that’s all it is–is to make common tasks easier to code for the developer by reducing repeated code.

Clarity… well that’s personal preference and not a valid argument.

Interesting… as a rule of thumb I dislike letting even template files run code directly, wrapping them in functions as well.

I’m writing the Mk8 version of my little CMS right now – it’s template loading function pretty much just includes the file, since the template is all functions.


	public function loadTemplate($name) {
		$fullName=safeName($name).'.template.php';
		if (file_exists($temp=$this->paths['LOCAL_THEME'].$fullName)) {
			safeRequire($temp);
			return true;
		} else if (file_exists($temp=$this->paths['LOCAL_ROOT'].'theme/default/'.$fullName)) {
			safeRequire($temp);
			return true;
		} else if (file_exists($temp=$this->paths['LOCAL_ROOT'].'modules/'.$name.'/'.$fullName)) {
			safeRequire($temp);
			return true;
		}
		return false;
	} // paladin::loadTemplate

Basically just calling my scope-breaking require wrapper since everything there is wrapped in functions too. It checks through each possible location in turn since if the current theme has it, it should run from there, otherwise run from default, otherwise use the copy that came with the ‘module’.

Then instead of increasing the memory footprint, I just pass the data by reference.

for example common.template.php


function theme_header(&$paladin,$admin=false) {
global $texts;

	foreach ($paladin->httpHeaders as $header) {
		header($header);
	}

	echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html
	xmlns="http://www.w3.org/1999/xhtml"
	lang="en"
	xml:lang="en"
><head>

etc… etc… etc… Another bonus is it lets me keep multiple common commands you know will be used, like theme_header, theme_footer, theme_subSectionStart, theme_subSectionEnd, all in one file/include.

Technically $paladin is a object so it’s always passed by reference on modern PHP flavors, but I like to state it with & just to be sure. In this version “paladin” is the core object, “mount” is the database connection, and modules are extensions of class “squire”… was thinking on having module sub-functions be “page”, but was worried people would confuse “page” as in printed with “page” as in pre-teen serf.

I believe you may have seen something similar as a project you were on for a short while was loosely based on my Mk6 that someone else is running with the concept of.

With yours, I’d suck it up and type the $variable[‘’] inside the template, rather than making duplicates of every variable in memory… of course that you’re passing the output on the stack means you really weren’t keeping memory use in mind… NOT that it’s easy to keep in mind with in any complex CMS – my own approach of “generate all the data before even making ANY output, even headers” troubles me in terms of the size of it’s memory footprint. I’m half tempted to let the routines that pull/process the data call the theme directly – but that goes against the entire “layered security” policy I’m working from… having that same type of setup WITH the overhead of markup added to it? Ouch.

Though it would STILL be leaner than any of the “templating engine” nonsense by a factor of four.

Ahhh me and that framework had a lot to disagree on :stuck_out_tongue:

I suppose there are just different ways of doing things; For example - I trust the developers. If they want to include a filename which is not ‘safe’, well I’d let them; If they wanted to do some damage they’d just write their own code anyway. If the developer was just being stupid - well, again, let them. My job is to make the framework work. I certainly do validation - I will check if a file exists, but not if it’s formatted correctly. Mainly, I have 0% trust in users, but 99% trust in the developers.

The variables aren’t duplicated in memory, because everything passed to that template (so far) has been an object - oh and a boolean or two. As for using an array… I dislike using an array unless everything within it is the same variable type. The only time I don’t is when passing an array to the above method, which I do inline.

Micro-optimisation (worrying about a variable or two being cloned) etc is certainly something I care little for. I don’t like wasting memory etc, but servers nowadays really don’t get affected unless you’re pulling in millions of views a day. By which point I’ve have sold up and started working on something new.

In the next few days I’ll possibly post a new framework I’ve been working on; but I’ll comment it all up first. I’ve been building it alongside a website for my university’s physics society ( Big leagues! :lol: ) and it times up pretty darn well.

I put your claim to the test. The difference between just one php tag vs multiple opened and closed tags is in the ballpark of one one-millionth of one millisecond. And neither approach was consistently faster than the other.

You may want to retract your “herpdaderp”.

And the next time you get the urge to insinuate that the smartest in the business are stupid, I strongly suggest you first test your claim, because your gut instinct doesn’t have the greatest track record.

Getting back to the original topic. I would like to think I know a little bit more than most coders about formatting text because I’ve actually had art classes on the topic as part of my college major. For all the bru ha ha ha going on the important part is missed - be consistent. Know your formatting rules, know why you made them, then you’ll know when to break them.

As for testing Jason’s claim…



$echoey = str_repeat("\\<\\?php echo 'Hello World'; \\?\\>", 10000);
$noEchoEy = str_repeat("echo 'Hello World';", 10000);

for($i=0;$i<1000;$i++) {
	ob_start();
	
	$before = microtime();
	eval($echoey);
	$echoEyExeTime[] = microtime() - $before;
	
	ob_end_clean();
	ob_start();
	
	$before = microtime();
	eval($noEchoEy);
	$noEchoEyExeTime[] = microtime() - $before;
	
	ob_end_clean();
}

$echoEyExeTime = array_sum($echoEyExeTime) / count($echoEyExeTime);
$noEchoEyExeTime = array_sum($noEchoEyExeTime) / count($noEchoEyExeTime);

echo "Execution time with tag wraps: {$echoEyExeTime}<br> Execution time without tag wraps: {$noEchoEyExeTime}";

I used a double looping to try to rule out the effect of other concurrent threads on the test. While the non Echoey method is faster, it’s hardly a speed revolution.

EDIT - Also noted this gem:

All objects in PHP are passed by reference anyway. Values aren’t copied in the PHP interpreter until the values become changed in different scopes. Are you sure you really understand how the Zend Engine works?

I tried to run your test, but I got syntax errors. In fact the docs for eval say that the code mustn’t be wrapped in opening and closing PHP tags. Also, probably best to pass “true” to microtime, otherwise it returns a string with a space in it, which doesn’t work well for arithmetic.

To make eval work in that way you’ll need to use:


eval('?>' . $echoey);

Well, someone make the corrections and run the test. I’m curious (also harried at work)

It turned out that most of the time was being spent on eval itself, so I change it up to instead require an actual template file.



<?php

// prepare template files
file_put_contents('one_tag.php', "<?php\
\
" . str_repeat("echo 'Hello World';\
", 10000));
file_put_contents('many_tags.php', str_repeat("<?php echo 'Hello World'; ?>\
", 10000));

$oneTagTimes = array();
$manyTagsTimes = array();

for ($i = 0; $i < 1000; $i++) {
    // test one tag
    ob_start();
    $before = microtime(true);
    require 'one_tag.php';
    $oneTagTimes[] = microtime(true) - $before;
    ob_end_clean();

    // test many tags
    ob_start();
    $before = microtime(true);
    require 'many_tags.php';
    $manyTagsTimes[] = microtime(true) - $before;
    ob_end_clean();
}

$oneTagAverage = array_sum($oneTagTimes) / count($oneTagTimes);
$manyTagsAverage = array_sum($manyTagsTimes) / count($manyTagsTimes);

echo "oneTagAverage -> $oneTagAverage\
",
     "manyTagsAverage -> $manyTagsAverage\
",
     "\
",
     "diff -> ", ($oneTagAverage - $manyTagsAverage), "\
";

I get a difference of about 0.002 milliseconds. And even that number is inflamed by a factor of 10 or more. Template files are usually nowhere near 10,000 lines (or at least mine aren’t). They’re closer to perhaps a few hundred, and most of those lines are plain HTML… which is the whole reason we choose to close PHP in the first place.

<chris tucker>DO YOU UNDERSTAND THE WORDS THAT ARE COMING OUT OF MY MOUTH!?!</chris tucker>

Quoting out of context too – given said statement was comparing to how Jake was using EXTRACT to take an array and/or object and put it in the local namespace? I AM using objects, it’s WHY I’m using objects and/or arrays, and it’s why I made that statement as he is not. Jake was using extract to make extra copies therein using more memory instead of passing by reference.

Care to share your ‘test’? Mike was nice enough to share a test – broken test since it doesn’t account for rollover/ms inaccuracy and doesn’t pass ‘true’ to microtime so none of the results make any sense (since the returned string is microseconds first, meaning his test can return negative values) – but at least it’s an attempt.

With 1000 per loop, and such a large output size, the timer isn’t likely firing and the numbers would be skewed due to malloc and garbage collection… Though I notice you did catch the incorrect use of microtime.

Funny, I get a five to nine percent speed difference in favor of without… consistently.

Basing off Mike’s code, we’ll switch it around to check for timer rollover since we don’t know the granularity, then set up to test for iterations over a fixed period of time rather than a fixed number of loops – 1) so we don’t have to wait forever, 2) again we don’t know the timer granularity/accuracy. A one second delay before each test should also give the _clean method enough time to get garbage collection out of the way – something that can wildly skew the numbers in favor of whoever goes first.

We’ll also pull the eval since that adds a lot of execution overhead, and we really don’t need 10000K loops to figure this out… 24 echo’s each should handle it quite nicely. We’ll also plug in a variable in addition to the literal so that we can test the ACTUAL difference in a ‘real world’ type scenario, and then change that variable so as to eliminate value caching as a possible effect on the test.

I also had to move the buffering around each call, as the malloc’s were triggering enough to effect the results… and blow past the 32 meg memory limit I have set up :smiley:

Something good to add is a routine that does everything except output the values - gives us a baseline we can subtract from our execution times.

Gah, code’s too long. I’ll upload it as .txt to my host (since it seems phps isn’t set up… new host, still adjusting to not running my own).

http://www.cutcodedown.com/for_others/pvpVsNoPhp/tagWrap.php.txt

Which on this lappy (2.4ghz Core 2) under XAMPP gave the following results:

http://www.cutcodedown.com/for_others/pvpVsNoPhp/PhpVsNoPhp.png

On my workstation the results are a bit lower - around 4.97% advantage as opposed to the 8.88% above - and the disparity does seem to drop the faster the CPU.

But still, we’re talking ~5%… though the real kicker is what happens if you put string additions in… compared to using period instead of comma’s on echos, string additions are many times worse; Combine the two, and well…

I would suspect you either had a flawed testing methodology, were testing on a machine fast enough to lower the difference, or had some other process or an inaccurate timer interfering with the results.

C is compiled to machine language, the abstaction exists to make it portable across CPU platforms/families, since machine language for x86 won’t run on ARM… or PPC… or MIPS… or 68k… or Z80… or 6809… or RCA 1802…

PHP is written in C and is interpreted so that it is easier to port across platforms without the endless low level hardware differences that you have to deal with in C getting in the way. Since most all of it’s functions are written in C they get the same speed as C, which is why PHP is best used as glue between compiled libraries (like mySQL, like Regex) instead of making complex userland functions.

TWIG takes something you can already do in PHP without the library and makes it cryptic, with an extra layer of abstraction for… for… for what exactly?!? For the sake of making it more complex and harder to use? To make the end result slower than Ruby? It does the opposite of what PHP is for, being glue, and instead treats it as a general purpose programming language… something it most certainly is not.

At least C and PHP have legitimate reasons for their abstractions.

After the adjustments I made to Mike’s test, his and mine are largely identical. The only significant difference is the code that was put in the templates.

In the “one_tag” template, I repeated this block 10 times:

if (isset($_SERVER['PHP_SELF'])) {
    echo '
        <div class="box">
             The value of PHP_SELF is ', htmlspecialchars($_SERVER['PHP_SELF']), '
        </div>
    ';
}

In the “many_tags” template, I repeated this block 10 times:

<?php if (isset($_SERVER['PHP_SELF'])): ?>
    <div class="box">
        The value of PHP_SELF is <?php echo htmlspecialchars($_SERVER['PHP_SELF']) ?>
    </div>
<?php endif ?>

The idea was to use templates closer to what real templates might be like.

I rechecked it just now, and using these templates with my tester above, neither one is consistently faster.

It apparently varies depending on what’s in the template. Nonetheless, we’re still talking about a fraction of a fraction of a fraction of a fraction of a fraction of a fraction of a millisecond – literally. To say that one is 9% faster is purely academic. For all practical purposes, they’re identical.

And the real issue here is that you insinuated that anyone who uses the open/close tag syntax is stupid, when in fact it’s a non-issue. <snip/>

It’s great that you ran some detailed tests just now. I can only hope that you’ll continue to run tests before you post. And if you do that, then you may be able to identify a way that the community can genuinely improve their code, and you’ll have evidence to back it up, which can lead to productive discussions.

I just ran deathshadow60’s file. the first are his results png, the second mine.

Windows 7 Home Premium
Intel(R) Core™ i3-2130 CPU @ 3.40GHz
6.00 GB
64-bit

Whether or not the amount of difference is substantial enough to justify changing coding habits is debatable, but it sure looks like a difference exists just the same.