Skip to content

Namespaces, use and autoload

A namespace is the first part of a class name. App\Text\Greeter is the class Greeter in the namespace App\Text. autoload finds the file of a class from its name, so a program never names the file.

Namespaces and use

A namespace is a prefix on every name a file declares, so two classes called Greeter in two parts of a program never get in each other's way.

A file may open with one namespace declaration, and any number of use imports after it. Both belong at the top of the file and never inside a class or a function. A name you write with a \ in it is read from the very beginning: Core\Str means Core\Str wherever you write it. A name with no \ is looked for in the file's imports first, then in the file's own namespace, and nowhere else.

Good to know: there is no falling back to the outermost level, so inside namespace App; a plain Helper means App\Helper and never a Helper declared outside any namespace. An import cannot be renamed and cannot name a group of names, so write one use per name. Core is reserved for the classes Novis ships, and nothing you write may live under it.

Put a file in a namespace

<?nvs
// One `namespace` declaration at the top of the file puts everything the file
// declares under that prefix. Inside the file you still write the short name.
namespace App;
class Greeter
{
public static function greet(string $name): string
{
return 'Hello, ' . $name . '!';
}
}
// The short name is looked for in the file's own namespace, so this is
// `App\Greeter`. Writing the name out in full means exactly the same class.
echo Greeter::greet('Ada'), "\n";
echo App\Greeter::greet('Bo'), "\n";
Output
Hello, Ada!
Hello, Bo!

Import the names you type a lot

<?nvs
// A `use` import lets you write a long name short. It covers the code below it
// and introduces one name, under the last part of the path.
namespace App;
use Core\Arr;
use Core\Str;
array<string> $words = ['order', 'invoice', 'receipt'];
// `Str` and `Arr` are the imports above.
echo Str::upper($words[0]), "\n";
echo Arr::count($words), "\n";
// You never have to import anything. A name written out in full works the
// same, imported or not.
echo Core\Str::lower('QUIET'), "\n";
Output
ORDER
3
quiet

Name a class after a built in and keep both

<?nvs
// Your program can have its own class called `Json`. A name that contains a `\`
// starts from the top namespace. So `Core\Json` is the built-in class, and
// `Json` is yours.
namespace App\Billing;
class Json
{
public static function forInvoice(int $number, int $totalCents): string
{
return Core\Json::encode({ invoice: $number, total: $totalCents });
}
}
echo Json::forInvoice(1042, 5990), "\n";
echo Core\Json::encode({ ok: 1 }), "\n";
Output
{"invoice":1042,"total":5990}
{"ok":1}

Details

The namespace declaration must come before every class, interface, enum and type alias in the file. A second namespace, or one below a declaration, does not compile (E0243). A use import covers the code below it. A class above the use cannot use the short name, so put every use at the top. A use inside a method body does not compile (E0233).

A name that starts with \, such as \Core\Str, does not compile (E0240). A name with a \ in it already starts from the top namespace. use Core\Str as S; does not compile (E0212), and neither does use Core\{Str, Json}; (E0238). namespace Core; does not compile (E0217). A class of your own may still be called Str, outside any namespace or inside one.

A class or an interface is declared at the top level of a file. A class inside an if or inside another class does not compile (E0233). An enum or a type alias may also be declared inside a class or an interface body. It has no public or other modifier in front of it (E0133).

Autoload

autoload tells Novis which folder your classes are in, so your program uses a class by its name and never loads a file.

One declaration connects the start of a namespace to a folder. With autoload 'App' from './src';, the class App\Text\Greeter is read from ./src/Text/Greeter.nvs. App is removed, the middle parts are folders, and the last part is the file name. One prefix can have several folders, and they are searched in the order you wrote them.

autoload discover 'Site' from '../../*/src'; uses every folder the pattern matches. The folder Shop/src is the namespace Site\Shop.

In autoload 'Site\{..}' from '../src';, {..} is replaced by the name of the folder that .. points to. In Blog/public, the prefix is Site\Blog.

autoload links reads a folder only for its routes. Your program can link to them but cannot call their classes. Both forms take it, as in autoload links discover 'Site' from '../../*/src';.

Good to know: every autoload declaration is read when the program is compiled. A class that cannot be found stops the compile with an error. nvs check --autoload-map shows which folders each prefix uses.

The examples below run with this configuration file.

nvs.toml
# The server serves files from this folder. Example 05 is mounted at /blog,
# and the start file of the Shop module is mounted at /shop.
[server]
root = "."
[[server.mount]]
prefix = "/blog"
entry = "05-link-to-another-module.nvs"
[[server.mount]]
prefix = "/shop"
entry = "modules/Shop/public/index.nvs"

Find a class by its name

<?nvs
// One line says where your classes live, and after that you name a class and
// never a file. `App\Text\Greeter` is read from `app/Text/Greeter.nvs`: the
// `App` prefix is dropped, and what is left becomes folders and a file name.
autoload 'App' from './app';
use App\Text\Greeter;
echo Greeter::hello('Alice'), "\n";
echo App\Text\Greeter::hello('Bo'), "\n";
Output
Hello, Alice!
Hello, Bo!

Put your own fix in front of an installed package

<?nvs
// One prefix can list several folders. `autoload` searches them in order and
// uses the first file it finds. Put the folder with your own fixes first.
// A class you did not fix is still loaded from the installed package.
autoload 'Acme' from './fixes', './vendor';
use Acme\Pdf\Reader;
use Acme\Pdf\Writer;
echo Writer::describe(), "\n";
echo Reader::describe(), "\n";
Output
writer: our patched copy
reader: the installed copy

Let a folder of packages name itself

<?nvs
// A project split into packages, each with its own `src` folder. `discover`
// takes the pattern once, and every folder that matches becomes the home of
// the namespace the `*` stands for. Adding a package needs no new line here.
autoload discover './packages/*/src';
use Billing\Invoice;
use Shipping\Label;
echo Invoice::number(1042), "\n";
echo Label::forOrder(1042, 'Lyon'), "\n";
Output
INV-1042
SHIP-1042 to Lyon

Share one start file between modules

<?nvs
// Every module in this project has the same start file, byte for byte.
// Each start file maps its own module. `{..}` in it becomes the name of the
// module's folder, so one file maps `Site\Blog` and the other `Site\Shop`.
require './modules/Blog/public/start.nvs';
require './modules/Shop/public/start.nvs';
echo Site\Blog\Home::title(), "\n";
echo Site\Shop\Home::title(), "\n";
Output
Blog home
Shop home

Link to another module

<?nvs
// Shows how a program builds a link to a page of another module.
// The `nvs.toml` next to this file mounts this file at `/blog` and the Shop module at `/shop`.
// `autoload links` reads the folder of each module only to find its routes.
// The program can build a link to a route of these classes. It cannot call their methods.
autoload links discover 'Site' from './modules/*/src';
use Core\Http\Method;
use Site\Shop\Cart;
if (Core\Env::context() == Core\Env::Context::Request) {
// The server mounts the Shop module at `/shop`, so the link starts with `/shop`.
echo Core\Router::url(Cart::show, ['id' => 3]);
} else {
// From the command line, this part sends one request to the mount `/blog`.
// This prints `/shop/cart/3`.
var $page = Core\Test::request(Method::Get, '/', { mount: '/blog' });
echo $page->body(), "\n";
}
Output
/shop/cart/3

Details

Every path in an autoload declaration is text in quotes, relative to the folder of the file that contains the declaration. A path in a variable does not compile (E0123). An autoload declaration is written at the top level of a file, and inside an if or a method it does not compile (E0233). It covers the whole file, so it may come after the code that uses its classes.

Every part of a prefix starts with a capital letter. A prefix such as 'app' or 'App\*' does not compile (E0327). One part may be {.}, {..} or {../..}. That part is replaced by the name of the folder the path points to from the declaring file.

A file found through autoload declares one class, interface, enum or type alias. Its full name, namespace included, must be the name the file was found by. Otherwise the program does not compile (E0317). Folder and file names are case-sensitive, so App\text\Greeter does not find Text/Greeter.nvs.

A class that no folder has is E0303, the same error as any name that is not declared. A folder that does not exist is allowed. nvs check --autoload-map prints every prefix with its folders, and lists a folder that does not exist under missing.

The map comes from every autoload in every file the program reads. Core\Program::implementing<I>() uses it too: it finds each class that implements the interface I, even when no code names the class.

The page Many modules on one server shows autoload discover and autoload links in a project with many modules.

  • Do give each class its own file, in the folder its namespace names.
  • Do write one autoload line in the file that starts your program.
  • Do write use for a class you name often, and the full name for one you name once.
  • Don’t use require to load a class. Use autoload, so the file is read only once.
  • Don’t start a name with a backslash. A name with a backslash in it is already the full name.