I am creating a website using the framework in this book and I’m at a point where I need to add “miscellaneous” functions.
For example, I have a requirement to display (in layout.html.php) a number and its ordinal (29th as opposed to just 29). I have the function to do this:
function ordinal($number)
{
$ends = array('th','st','nd','rd','th','th','th','th','th','th');
if ((($number % 100) >= 11) && (($number%100) <= 13))
return $number. 'th';
else
return $number. $ends[$number % 10];
}
I can call this with:
echo ordinal(29);
Ok, my problem is (and I suppose this is because I am still learning to structure code in a framework) is:
-
Not sure WHERE to put the function, and
-
How to call it from THAT location
Here’s what I’ve tried and how I’ve thought about it…
The function is something I could use in ANY website so it could go into the framework part of the site rather than the specific-project part. I’ve called my framework… er… Framework (as opposed to Ninja in the book). Also, thinking ahead, I may have other useful, but miscellaneous, functions.
So, I created a class called FunctionLibrary (which I may later split into separate classes if logical groups emerge) and added it to the Framework namespace. And I put my function in there.
Here we go:
<?php
namespace Framework;
class FunctionLibrary
{
public function __construct()
{
}
function ordinal($number)
{
$ends = array('th','st','nd','rd','th','th','th','th','th','th');
if ((($number % 100) >= 11) && (($number%100) <= 13))
return $number. 'th';
else
return $number. $ends[$number % 10];
}
}
So…
- Is this logic (to put the function here) good?
- If so, is the class OK (little bit new to custom classes and unsure about that empty constructor - used to passing stuff in)
- If so, how can I call it from my template? I have tried:
echo ordinal($years);
echo FunctionLibrary ordinal($years);
echo Framework\FunctionLibrary ordinal($years);
I don’t think I need a leading slash, this is not a built-in function. None of these work:
Fatal error: Uncaught Error: Call to undefined function ordinal() in /var/www/<domain>/templates/layout.html.php on line *228*
Ideas?