Jump to content

Correct Namespace for Module Classes within modules folder


cosmicsafari
 Share

Recommended Posts

Hi All,

Fairly new to ProcessWire so apologies if this is a daft question, but I am having a go creating my first module. I have set it up and enabled it as per the docs.

However I have created another class within the same module directory, which was going to be used in the main module file but I can't get it to work for the life of me and I believe its due to me not fully understanding the namespace side of things.

Example:

MyModule.module.php

<?php
namespace ProcessWire;

class MyModule extends WireData implements Module
{
    public static function getModuleInfo()
    {
        return array(
            'title' => 'Test Module',
            'version' => 1,
            'summary' => 'Test module',
            'href' => '',
            'singular' => true,
            'autoload' => true,
            'icon' => 'exchange',
        );
    }
    public function newMethod(
      $testMessage
    ) {
        $foo = new Foo($testMessage);
        $foo->getFoo();
    }
}

Foo.php

<?php
namespace ProcessWire;

class Foo {

    protected $foo;

    public function __construct($foo)
    {
        $this->foo = $foo;
    }

    public function getFoo()
    {
        return $this->foo;
    }
}

Now as I understand it both these files should exist under the ProcessWire namespace, so in theory I should be able to use Foo within MyModule without any use statements as they both exist at the same level within the ProcessWire namespace?

However when I try something like so:

$myModule = $modules->getModule('MyModule');
$myModule->myMethod('Foo');

I would have thought this should return 'Foo', however I keep running into errors like:

Quote

"Error: Class 'ProcessWire\Foo' not found"

Any help would be appreciated.

Link to comment
Share on other sites

@cosmicsafari. Welcome to the forums and ProcessWire.

You will need to include your Foo.php file in your module ( MyModule.module). ProcessWire doesn't know about it and will not include it for you. You can require it outside the class or in its __construct() or function init() methods (I think either of the three should work).

$dir = dirname(__FILE__); 
require_once($dir . "/Foo.php");

Maybe it was just a typo, but module files end in .module (that's the extension, not .php)

  • Like 4
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...