Class loading and referencing

Class loading and referencing

per Phil McCurdy,
Number of replies: 3

By way of introduction, I'm an experienced developer but new to both php and Moodle, so please forgive a rather basic question.

Currently developing a custom auth plugin and would like to create a separate class for some utility methods.

I've created /auth/org/classes/myclass.php:

class auth_plugin_org_myclass
{
    function myfunction(){
        return "foo";
    }
}

Calling from /auth/org/auth.php:
        $myc = new auth_plugin_org_myclass();
        $bar = $myc->myfunction();

throws an exception "Exception - Class 'auth_plugin_lifesaving_myclass' not found"

Moodle caches have been purged (multiple times)
I can't help feeling that I'm missing something basic.


Average of ratings  -
In reply to Phil McCurdy

Re: Class loading and referencing

per Leon Stringer,
Avatar Core developers Avatar Particularly helpful Moodlers

Assuming your plugin is in /auth/org then I think /auth/org/classes/myclass.php should be:

namespace auth_org;

class myclass
{
    function myfunction(){
        return "foo";
    }
}

Then /auth/org/auth.php is:

        $myc = new auth_org\myclass();
        $bar = $myc->myfunction();

There's some documentation on Moodle's class loading which may help.

In reply to Leon Stringer

Re: Class loading and referencing

per Davo Smith,
Avatar Core developers Avatar Particularly helpful Moodlers Avatar Peer reviewers Avatar Plugin developers
In theory:
class auth_org_myclass {
...
}

(without the namespace, and without the word 'plugin' in the class name) would also work, but that is now deprecated, so you should definitely be using the namespace version for new code.