2

PHP experts! I'm trying to make my code more modular according to the ways of PHP (using 7.0) and this is my first experiment creating my own combination of namespace + composer package + git repository.

My package directory:

packagedir
|__src
|   |__myfunc.php
|__composer.json

myfunc.php:

namespace MyNS\MySubNS;
function myfunc() { return 1; }

packagedir/composer.json:

{
  "name": "myns/mysubns",
  ...
  "autoload": {
    "psr-4": { "MyNS\\MySubNS\\": "src" }
  }
}

All checked into repository packagedir/.git.

My project directory after composer install:

public_html
|__vendor
|   |__composer
|   |   |__ [all the usual autoload_* stuff, etc.]
|   |__myns
|   |   |__mysubns 
|   |       |__src
|   |       |   |__myfunc.php
|   |       |__composer.json
|   |__autoload.php
|__composer.json
|__composer.lock
|__index.php

public_html/composer.json:

{
  "require": {
    "myns/mysubns": "dev-master"
  },
  "repositories": [
    { "type": "git",
      "url": "file:///path/to/packagedir/.git" }
  ]
}

index.php:

ini_set('display_errors','1');
require_once 'vendor/autoload.php';
echo \MyNS\MySubNS\myfunc();

It looks like composer installed the package in vendor, and autoload_ps4.php includes:

return array(
    'MyNS\\MySubNS\\' => array($vendorDir . '/myns/mysubns/src'),
);

But I get:

( ! ) Fatal error: Uncaught Error: Call to undefined function MyNS\MySubNS\myfunc() in /var/www/public_html/index.php on line 3
( ! ) Error: Call to undefined function MyNS\MySubNS\myfunc() in /var/www/public_html/index.php on line 3

Can anyone see what I'm doing wrong (aside from the advice that .git repositories are not recommended as a place to get packages)?

1

1 Answer 1

4

PHP does not autoload functions. Use the files autoloader, eg:

{
    "autoload": {
        "files": ["src/MyLibrary/functions.php"]
    }
}

or enclose them in a class and autoload that, eg:

namespace foo;
class Helper {
    public static function foo() { ... }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Perfect! Thank you very much!
This was very helpful. I was wondering why my custom package was not working and it was because it uses a file. Your first suggestion of using the "files" autoloader was spot on. Thank you @Sammitch

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.