Jump to content

Recommended Posts

I am trying to be true to the principle that logic and presentation should be kept separate.

 

However, the only way to generate dynamic content and output is using something like PHP, so there is somewhat of a conflict.

 

I just wrote this Function, and I am curious if it breaks the principle above...

/**
 * Returns Online Status Indicator Markup
 *
 * Takes User's Last Activity and determines the User's Online Status.
 * Returns HTML for appropriate Online Status Indicator.
 *
 * @param		DateTime $lastActivity	MySQL DateTime format (yyyy-mm-dd hh:mm:ss)
 * @return	string
 */
function getOnlineStatus($lastActivity){
	// strtotime() converts DateTime format (yyyy-mm-dd hh:mm:ss) into a Unix Timestamp (seconds).
	// time() is current time measured in the # of seconds since Unix Epoch (January 1 1970 00:00:00 GMT).
	$minutesOnline = (time() - strtotime($lastActivity))/60;

	// Determine Online Status.
	if ($minutesOnline < 15){
		// Member Online
		$indicator = '<img src="/images/Light_Green_10.png" width="10" alt="Member Online" /><br />';
	}else if ($minutesOnline < 30){
		// Member Idle
		$indicator = '<img src="/images/Light_Yellow_10.png" width="10" alt="Member Idle" /><br />';
	}else{
		// Member Offline
		$indicator = '<img src="/images/Light_Gray_10.png" width="10" alt="Member Offline" /><br />';
	}

	return $indicator;
}//End of getOnlineStatus

 

Thanks,

 

 

Debbie

 

 

There are times when one must blend/merge/use php within htlm output. it is not a question of separating logic FROM html. what if your options were numbers rather than html code? (rhetorical)

 

Your function is a logical function.

 

Consider when one is echoing a result set from a query - is that  logic or presentation? (also rhetorical)

There are times when one must blend/merge/use php within htlm output. it is not a question of separating logic FROM html. what if your options were numbers rather than html code? (rhetorical)

 

Your function is a logical function.

 

Consider when one is echoing a result set from a query - is that  logic or presentation? (also rhetorical)

 

The reason I don't feel I made any great sins is that my Function's main purposes include...

- Compartmentalizing and re-using code that is used in multiple places

- Capturing business "logic" to determine a Member's Online Status

- Assign the proper HTML to a variable

 

It is not like I am just echoing HTML inside the Function - which of course would be bad.

 

I use the Function to determine the *right* HTML, but then let my main script do the displaying.

 

 

Debbie

 

 

However, the only way to generate dynamic content and output is using something like PHP, so there is somewhat of a conflict.

 

Separating logic from presentation (html or whatever) is about separating business rules out from the html.  For example you don't want to have your form validation code and database stuff like adding a user or updating records embedded inside your html.  You keep that all separate in the file and then call up the appropriate templates/view based on how the business logic runs.

 

There is such a thing as 'display logic' and that usually does go into the templates/html.  This is why most template systems have support for basic control structures such as loops and if/else statements, as well as some ways to manipulate variables such as htmlentities or urlencode.  You should not need to do anything more complex that that inside your template files.

 

 

What you have there for a function is an acceptable usage.  You could still split it if you wanted to and assign $minutesOnline (or something similar) as a variable in your template and then inside your template have an if statement to choose the appropriate image to use.  That would allow you to easily use text instead of an image in a different template or area if you decided you want to do that.

 

 

 

 

Yea it's acceptable, I don't whana act a smartass but you could tweek it abit for changeing stuff later in it :)

For example, you can make you'r self or others who work or will work with you, a life easyer later on by flexible image changeing, same you can do with

'width' or 'alt'.

 


class onlineStat{

public function runOnlineStatus($lastActivity,$onlineImg,$idleImg,$offlineImg){
	//Set the time
	$minutesOnline = $this->setTime($lastActivity);

	if ($minutesOnline < 15){
		$indicator = $this->online($onlineImg);
	}
	else if ($minutesOnline < 30){
		$indicator = $this->idle($idleImg);
	}
	else{
		$indicator = $this->offline($offlineImg);
	}

	return $indicator;
}

// time unix
public function setTime($lastActivity){
	$minutesOnline = (time() - strtotime($lastActivity))/60;
	return $minutesOnline;
}

// set images for statuses
public function online($img){
	$indicator = '<img src="images/'.$img.'" width="10" alt="Member Online" /><br />';
	return $indicator;
}
public function idle($img){
	$indicator = '<img src="images/'.$img.'" width="10" alt="Member Online" /><br />';
	return $indicator;
}
public function offline($img){
	$indicator = '<img src="images/'.$img.'" width="10" alt="Member Online" /><br />';
	return $indicator;
}

}

/** So now you can go like this in you'r html */

// Your last activity string
$lastActivity;

//Run the class
$onlineStatus = new onlineStat;
//set Images
$onlineImg = "Light_Green_10.png";
$idleImg = "Light_Yellow_10.png";
$offlineImg = "Light_Gray_10.png";

//get Indicator
$indicator = $onlineStatus->runOnlineStatus($lastActivity,$onlineImg,$idleImg,$offlineImg);

 

Hope it helps :)

It can be okay, in some situations. I don't feel that your example is one of them. Mixing in random HTML all over your application is a major headache to maintain.

 

So what would you do?

 

(Please stick with procedural code, as OOP will go over my head...)

 

 

Debbie

Ideally, you want all of your written language defined in a single file, or folder for large projects. You want to add a prefix to the file name that represents the language the text is in. Something like en.lang.php or lang.en.php

 

This file will be included into another file, that holds all of your HTML. Again, you may want a different file for each page, depending on how much mark up each page has. You can name these home.html.php, profile.html.php, etc. Something that will be easy to find when you're trying to output that page. You also probably want a generic.html.php, that holds the header, footer etc, and can be included in each *.html.php file. You can go as far as putting these files into their own folder, template_name/whatever.html.php. That way, if you ever want to have multiple templates, your script only needs to grab the files from the 'thisTemplate' folder rather than the 'defaultTemplate' folder.

 

You can then build a parser that handles your view logic. This parser could be as simple as swapping placeholders for variables, or as complex as having a looping pattern. IF you want to avoid parsers, I don't think there's anything wrong with including a _little_ logic along with your markup, just keep it as generic as possible, and remember you're going to have to repeat this logic for every template you make.

 

This is a very simplified design of an extremely flexible, well organized display logic. Implementing it can be quite a bit of work, but updating is a breeze. The more generic you can make your logic, the more you can reuse for future projects down the road, the less work it is to implement.

It can be okay, in some situations. I don't feel that your example is one of them. Mixing in random HTML all over your application is a major headache to maintain.

 

So what would you do?

 

(Please stick with procedural code, as OOP will go over my head...)

 

I would use some sort of template system. I have posted a very basic snippet several times on these boards, and I'm pretty sure at least one of them was for you.

 

You can then build a parser that handles your view logic. This parser could be as simple as swapping placeholders for variables, or as complex as having a looping pattern. IF you want to avoid parsers, I don't think there's anything wrong with including a _little_ logic along with your markup, just keep it as generic as possible, and remember you're going to have to repeat this logic for every template you make.

 

I would have to say avoid making parsers. Ultimately it doesn't make any sense to use a parser and you're just creating more work for yourself with no reward. Simple conditionals and loops in a template is perfectly fine. It's either you put it in the template or you put it in the script calling the template, but that will cripple the usability of the data and you'll probably be sticking HTML into the calling script at that point.

Parsers are arguable, that's for sure. It really depends, do you want non-coders to design templates? If so, using pseudo-code is a great idea. A well made parser doesn't add that much overhead. Due to the generally static nature of a template, it's quite easy to cache the resulting code, or 'build' the pseudo-code into a PHPd version, if the overhead becomes a problem.

 

Your point is very valid though, I just tried to be very flexible in my answer. I generally don't follow my own advice, and hard-code the language directly in to the template, but I only occasionally have clients that care about anything beyond English.

do you want non-coders to design templates? If so, using pseudo-code is a great idea.

 

Why though? PHP code is almost identical to most template parser languages, only it is: better document, more consistent, and easier to find help with. I think it is just as difficult to learn Smarty as it is to learn a few basic things about PHP. And if you can use Smarty, you should have no problem doing the same things with PHP.

 

Just my opinion.

Agreed, but I find Smarty to be it's own language :D When I say pseudo-code, I mean placeholders with 'no value' alternative text, along with loops

 

A pseudo-code with placeholder design:

Saves your designer from having to enter/leave/worry about <?php ?> mode.

Saves you from having to verify if a variable is actually set before trying to use it (avoid notice)

Allows you to handle template errors separately, rather than having PHP thrown errors

Probably more...

 

Again, I see what you're saying, but there are a lot of language subtleties we developers take for granted :)

I just use PHP for my template language, I figure anyone can learn the basics of that just as well as they could a custom template language. 

 

The only nice thing about a custom template language would be the ability to shorten certain operations that can get a bit tedious when doing templates, especially forms.  I do run my templates through a sort of pre-parser to handle a few things, such as re-writing <?= to <?php echo so that it works even if short_open_tag is disabled.  I also turn error reporting down to exclude notices and warnings when the template is being run to hide any undefined variable notices or foreach warnings (they are still logged to a file and eventually fixed as time permits).

 

So what would you do?

 

As others have mentioned, I would make the display part of your template/view and put the conditional there.  Then just assign some variables to the template you can use to pick the proper value.  For example:

function getOnlineStatus($lastActivity){
$minutesOnline = (time() - strtotime($lastActivity))/60;

if ($minutesOnline < 15){
	// Member Online
	$indicator = 'online';
}else if ($minutesOnline < 30){
	// Member Idle
	$indicator = 'idle';
}else{
	// Member Offline
	$indicator = 'offline';
}

return $indicator;
}

function runTemplate($file, $vars){
include($file);
}

$user = /* Get the user information from somewhere */;

$tplVars = array(
'name' => $user['name'],
'image' => $user['profilePic'],
'onlineStatus' => getOnlineStatus($user['lastActivity']),
'bio' => $user['bio']
);

runTemplate('user_profile.tpl', $tplVars);

 

Then in your user_profile.tpl file:

<div id="profileImage">
<img src="<?php echo $vars['image']; ?>"><br>

<?php if ($vars['onlineStatus']=='online'): ?><img src="/images/Light_Green_10.png" width="10" alt="Member Online">
<?php elseif ($vars['onlineStatus']=='idle'): ?><img src="/images/Light_Yellow_10.png" width="10" alt="Member Idle">
<?php else: ?><img src="/images/Light_Gray_10.png" width="10" alt="Member Offline">
<?php endif; ?>
</div>

<h1><?php echo htmlentities($vars['name']); ?></h1>
<p><?php echo nl2br(htmlentities($vars['bio'])); ?></p>

 

Separating logic from presentation (html or whatever) is about separating business rules out from the html.  For example you don't want to have your form validation code and database stuff like adding a user or updating records embedded inside your html.  You keep that all separate in the file and then call up the appropriate templates/view based on how the business logic runs.

 

There is such a thing as 'display logic' and that usually does go into the templates/html.  This is why most template systems have support for basic control structures such as loops and if/else statements, as well as some ways to manipulate variables such as htmlentities or urlencode.  You should not need to do anything more complex that that inside your template files.

 

 

My thought too. Don't use the code in a function, just put the code in a seperate file in your templates folder and include it.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.