Docs / Digging Deeper / Package Development
Package Development
Introduction
Packages are the primary way of adding functionality to laraflare. Packages might be anything from a great way to work with dates to a package that allows you to associate files with Eloquent models.
There are different types of packages. Some packages are stand-alone, meaning they work with any JavaScript framework. Any of these packages may be used with laraflare by installing them with npm install.
On the other hand, other packages are specifically intended for use with laraflare. These packages may have routes, controllers, views, and configuration specifically intended to enhance a laraflare application. This guide primarily covers the development of those packages that are laraflare specific.
Creating a Package
A laraflare package is an ordinary npm package that depends on @laraflare/framework and exports a service provider. Its package.json names the provider so that it can be discovered (see Package Discovery).
A Note on Facades
When writing a laraflare application, it generally does not matter if you use contracts or facades since both provide essentially equal levels of testability. However, when writing packages, your package will not typically have access to all of laraflare's testing helpers, so write your package's tests against the framework's own classes, as an application's tests do.
Package Discovery
A laraflare application's bootstrap/providers.ts file contains the list of service providers that should be loaded by laraflare. However, instead of requiring users to manually add your service provider to the list, you may define the provider in the laraflare section of your package's package.json file so that it is automatically loaded. A provider is a module specifier, with the name of its export after a # (the module's default export when there is none). In addition to service providers, you may also list any facades you would like to be registered as aliases:
"laraflare": {
"providers": [
"@acme/courier#CourierServiceProvider"
],
"aliases": {
"Courier": "@acme/courier#Courier"
}
}
Once your package has been configured for discovery, laraflare will automatically register its service providers when it is installed, creating a convenient installation experience for your package's users. The package:discover Artisan command reads each installed package's laraflare section and writes the manifest, bootstrap/cache/packages.json, and bootstrap/cache/packages.ts, the module a Worker starts from, which registers the same providers:
npx artisan package:discover
Note
A Worker has no
node_modulesfolder to discover packages in, which is whypackage:discoverwritesbootstrap/cache/packages.tsahead of time (see Deployment). It leaves out the providers of the application'sdevDependencies, and the deferred ones.
Opting Out of Package Discovery
If you are the consumer of a package and would like to disable package discovery for a package, you may list the package name in the laraflare section of your application's package.json file:
"laraflare": {
"dont-discover": [
"@acme/courier"
]
}
You may disable package discovery for all packages using the * character inside of your application's dont-discover directive:
"laraflare": {
"dont-discover": [
"*"
]
}
Service Providers
Service providers are the connection point between your package and laraflare. A service provider is responsible for binding things into laraflare's service container and informing laraflare where to load package resources such as views, configuration, and language files.
A service provider extends the ServiceProvider class, exported by @laraflare/framework, and contains two methods: register and boot. The framework is a dependency of your own package. To learn more about the structure and purpose of service providers, check out their documentation.
Resources
Note
A Worker cannot load files by path, so where laraflare takes a path in the other places, a package hands over the value itself: the configuration object, the translation lines, or a function that imports the routes file. Only the files a package publishes are paths.
Configuration
Typically, you will need to publish your package's configuration file to the application's config directory. This will allow users of your package to easily override your default configuration options. To allow your configuration files to be published, call the publishes method from the boot method of your service provider:
import { fileURLToPath } from 'node:url';
import { ServiceProvider } from '@laraflare/framework';
const root = fileURLToPath(new URL('..', import.meta.url));
export class CourierServiceProvider extends ServiceProvider {
/**
* Bootstrap any package services.
*/
boot(): void {
this.publishes({
[`${root}config/courier.ts`]: 'config/courier.ts',
});
}
}
Now, when users of your package execute the vendor:publish command, your file will be copied to the specified publish location. Once your configuration has been published, its values may be accessed like any other configuration file:
import { config } from '@laraflare/framework';
const value = config('courier.option');
Default Package Configuration
You may also merge your own package configuration with the application's published copy. This will allow your users to define only the options they actually want to override in the published copy of the configuration file. To merge the configuration values, use the mergeConfigFrom method within your service provider's register method.
The mergeConfigFrom method accepts your package's configuration object as its first argument and the name of the application's copy of the configuration file as its second argument:
import courier from '../config/courier';
/**
* Register any package services.
*/
register(): void {
this.mergeConfigFrom(courier, 'courier');
}
Warning
This method only merges the first level of the configuration object. If your users partially define a multi-dimensional configuration object, the missing options will not be merged. The
replaceConfigRecursivelyFrommethod, which takes the same arguments, merges nested objects too.
Routes
If your package contains routes, you may load them using the loadRoutesFrom method. It takes a function that imports your routes file:
/**
* Bootstrap any package services.
*/
async boot(): Promise<void> {
await this.loadRoutesFrom(() => import('../routes/web'));
}
Migrations
If your package contains database migrations, you may use the publishesMigrations method to inform laraflare that the given directory or file contains migrations. When laraflare publishes the migrations, it will automatically update the timestamp within their filename to reflect the current date and time:
/**
* Bootstrap any package services.
*/
boot(): void {
this.publishesMigrations({
[`${root}database/migrations`]: 'database/migrations',
});
}
Language Files
If your package contains language files, you may use the loadTranslationsFrom method to hand laraflare the lines, by locale and file, under your package's name. For example, if your package is named courier, you should add the following to your service provider's boot method:
/**
* Bootstrap any package services.
*/
boot(): void {
this.loadTranslationsFrom({
en: { messages: { welcome: 'Welcome' } },
}, 'courier');
}
Package translation lines are referenced using the package::file.line syntax convention. So, you may load the courier package's welcome line from the messages file like so:
import { trans } from '@laraflare/framework';
console.log(trans('courier::messages.welcome'));
The lines in the application's lang/vendor/courier directory win over the package's, so your users can override them.
You can register JSON translation lines for your package using the loadJsonTranslationsFrom method. This method accepts the lines by locale:
/**
* Bootstrap any package services.
*/
boot(): void {
this.loadJsonTranslationsFrom({
en: { 'Hello': 'Hello' },
});
}
Views
Note
laraflare's screens are Vue components in
resources/js(see Views); a package's components are Vue components too, so there are none to register here.
To register your package's views with laraflare, you need to tell laraflare where the views are located. You may do this using the service provider's loadViewsFrom method. The loadViewsFrom method accepts two arguments: the path to your view templates and your package's name. For example, if your package's name is courier, you would add the following to your service provider's boot method:
/**
* Bootstrap any package services.
*/
boot(): void {
this.loadViewsFrom(`${root}resources/views`, 'courier');
}
Package views are referenced using the package::view syntax convention. So, once your view path is registered in a service provider, you may load the dashboard view from the courier package like so:
Route.get('/dashboard', () => view('courier::dashboard'));
Overriding Package Views
When you use the loadViewsFrom method, laraflare actually registers two locations for your views: the application's resources/views/vendor directory and the directory you specify. So, using the courier package as an example, laraflare will first check if a custom version of the view has been placed in the resources/views/vendor/courier directory by the developer. Then, if the view has not been customized, laraflare will search the package view directory you specified in your call to loadViewsFrom. This makes it easy for package users to customize / override your package's views.
Publishing Views
If you would like to make your views available for publishing to the application's resources/views/vendor directory, you may use the service provider's publishes method. The publishes method accepts an object of package view paths and their desired publish locations:
/**
* Bootstrap the package services.
*/
boot(): void {
this.loadViewsFrom(`${root}resources/views`, 'courier');
this.publishes({
[`${root}resources/views`]: 'resources/views/vendor/courier',
});
}
Now, when users of your package execute the vendor:publish Artisan command, your package's views will be copied to the specified publish location.
"About" Artisan Command
The built-in about Artisan command provides a synopsis of the application's environment and configuration. Packages may push additional information to this command's output via the AboutCommand class. Typically, this information may be added from your package service provider's boot method:
import { AboutCommand } from '@laraflare/framework';
/**
* Bootstrap any package services.
*/
boot(): void {
AboutCommand.add('My Package', () => ({ Version: '1.0.0' }));
}
Commands
To register your package's Artisan commands, you may use the commands method. This method expects command classes. Once the commands have been registered, you may execute them using the Artisan CLI:
import { InstallCommand } from './Console/Commands/InstallCommand';
import { NetworkCommand } from './Console/Commands/NetworkCommand';
/**
* Bootstrap any package services.
*/
boot(): void {
if (this.app.runningInConsole()) {
this.commands([
InstallCommand,
NetworkCommand,
]);
}
}
Optimize Commands
The optimize command runs the Artisan commands the framework and its packages have registered, and optimize:clear clears what they made. Using the optimizes method, you may register your package's own Artisan commands that should be invoked when the optimize and optimize:clear commands are executed:
/**
* Bootstrap any package services.
*/
boot(): void {
if (this.app.runningInConsole()) {
this.optimizes({
optimize: 'package:optimize',
clear: 'package:clear-optimizations',
});
}
}
Reload Commands
The reload command runs the commands registered for it. Using the reloads method, you may register your package's own Artisan commands that should be invoked when the reload command is executed:
/**
* Bootstrap any package services.
*/
boot(): void {
if (this.app.runningInConsole()) {
this.reloads('package:reload');
}
}
Public Assets
Your package may have assets such as JavaScript, CSS, and images. To publish these assets to the application's public directory, use the service provider's publishes method. In this example, we will also add a public asset group tag, which may be used to easily publish groups of related assets:
/**
* Bootstrap any package services.
*/
boot(): void {
this.publishes({
[`${root}public`]: 'public/vendor/courier',
}, 'public');
}
Now, when your package's users execute the vendor:publish command, your assets will be copied to the specified publish location. Since users will typically need to overwrite the assets every time the package is updated, they may use the --force flag:
npx artisan vendor:publish --tag=public --force
Publishing File Groups
You may want to publish groups of package assets and resources separately. For instance, you might want to allow your users to publish your package's configuration files without being forced to publish your package's assets. You may do this by "tagging" them when calling the publishes method from a package's service provider. For example, let's use tags to define two publish groups for the courier package (courier-config and courier-migrations) in the boot method of the package's service provider:
/**
* Bootstrap any package services.
*/
boot(): void {
this.publishes({
[`${root}config/courier.ts`]: 'config/courier.ts',
}, 'courier-config');
this.publishesMigrations({
[`${root}database/migrations/`]: 'database/migrations',
}, 'courier-migrations');
}
Now your users may publish these groups separately by referencing their tag when executing the vendor:publish command:
npx artisan vendor:publish --tag=courier-config
Your users can also publish all publishable files defined by your package's service provider using the --provider flag:
npx artisan vendor:publish --provider="CourierServiceProvider"