Reputation: 48
I'm trying to implement global functions by classes using laravel, heres my aproach:
Create a new class: app/libraries/regex.class.php
:
class Regex{
public static function isUsername($username){
$regex = "/^[a-zA-Z0-9_]+$/";
if (preg_match($regex, $username))
return true;
else
return false;
}
}
add the new library folder to app/start/global.php
:
ClassLoader::addDirectories(array(
app_path().'/commands',
app_path().'/controllers',
app_path().'/models',
app_path().'/database/seeds',
app_path().'/libraries',
));
then use the function in a view called by a route:
if(Regex::isUsername($_REQUEST['username'])==true){
echo "<br><br>did it";
}
else{
echo "<br><br>failed it";
}
if i put the isUsername()
function at the top of the view that i use it in it works just fine but trying to make it global throws an error. however i get: Class 'Regex' not found
on the line in the view where i try to use it. obviously it's not getting the class but i dont understand why?
edit: I was able to get it to work by adding require app_path().'/libraries/regex.class.php';
to the end of the global file, it works now, but i would still like to know why the original atempt at autoloading didnt work
Upvotes: 2
Views: 276
Reputation: 4411
You should name your file according to the class it contains, so in this case it should be named Regex.php
. The Laravel classloader looks for classes in files named this way.
You should also make sure you've added your libraries folder to the autoload.classmap section in composer.json.
Upvotes: 1