devs
devs

Reputation: 541

Laravel - Loading classes

There are questions on here and around Google asking about the same thing, but being a noob, I'm still not getting this. I'm using Laravel 4.

Trying to have a file for random classes. Doesn't load.

The class is in:

app/classes/Helpers.php

Helpers.php:

class Helpers {

    public function randomLowerCase($amount)
    {
        strtolower($str_random($amount))
    }

};

I've placed my classes in composer.json.

"classmap": [
    "app/commands",
    "app/controllers",
    "app/models",
    "app/classes",
    "app/database/migrations",
    "app/database/seeds",
    "app/tests/TestCase.php"
]

autoload_classmap.php:

'Helpers' => $baseDir . '/app/classes/Helpers.php',

And also ran

composer dump-autoload

I'm running the function in a UserController.php file in controllers, but I keep getting Call to undefined function randomLowerCase()

Upvotes: 0

Views: 5402

Answers (1)

Matt Stauffer
Matt Stauffer

Reputation: 2742

The problem is that you're not instantiating an instance of the Helpers class before you call one of its methods. You'll want to do one of the following:

First, keeping your class as it is, you could create an instance in the controller and call your method on it:

// Controller
$helpers = new Helpers;
$helpers->randomLowerCase($str);

Or, you could make the method static and call it as a static method:

// Helpers.php
class Helpers
{
    public static function randomLowerCase($amount)
    {
        strtolower($str_random($amount))
    }

};

// Controller
Helpers::randomLowerCase($str);

The error you're getting is because you're running the randomLowercase method as if it were just a function; methods are functions attached to a class/object.

Upvotes: 1

Related Questions