Class loading and referencing

Class loading and referencing

by 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

by Leon Stringer -
Picture of Core developers Picture of 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

by Davo Smith -
Picture of Core developers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of 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.

In reply to Davo Smith

Re: Class loading and referencing

by Phil McCurdy -
Thank you both. The namespace version works and has me back on track.