Richard Kiefer
Richard Kiefer

Reputation: 1954

How to autoload package's classes from within the package?

The application layout with my composer package is as follows

some-application
├── index.php
└── composer.json
└── vendor/my/package
              ├── composer.json
              └── src
                  ├── Foobar
                  │   └── style.css.php
                  └── Bar
                      ├── Moo.php
                      └── Baz.php

index.php uses style.css.php as a stylesheet in its html markup. The stylesheet is a php file because the styles need to get rendered dynamically. So, style.css.php is accessed directly by the clients browser, without passing index.php that includes the autoloader.

Now, I would like to access Moo and Baz in style.css.php, but what is the correct approach to define some kind of autoloader for my package that allows this?

I was only able to find info regarding the autoloader that the application would include. But what if I bypass the application's autoloader invocation?

Any advice is much appreciated, thanks.

Upvotes: 1

Views: 148

Answers (1)

delboy1978uk
delboy1978uk

Reputation: 12365

To autoload composer package classes, you just need to somehow load the autoloader.

In your script, you can say:

<?php

$path = file_exists('vendor/autoload.php') ? 'vendor/autoload.php' : '../../../autoload.php';
require_once $path;

use Bar\Moo;

$moo = new Moo();

This will load the application's autoloader when the package is included in an application, or will load the package's own autoloader when you develop the package, e.g. running tests.

Upvotes: 3

Related Questions