Application(应用程序)
Application 类负责连接 AdonisJS 应用程序的所有繁重工作。你可以使用此类来了解应用程序运行的环境、获取应用程序的当前状态或创建指向特定目录的路径。
另请参阅:应用程序生命周期
环境
环境指的是应用程序的运行时环境。应用程序始终在以下已知环境之一中启动。
web环境指的是为 HTTP 服务器启动的进程。console环境指的是除 REPL 命令之外的 Ace 命令。repl环境指的是使用node ace repl命令启动的进程。最后,
test环境指的是使用node ace test命令启动的进程。
你可以使用 getEnvironment 方法访问应用程序环境。
import app from '@adonisjs/core/services/app'
console.log(app.getEnvironment())你也可以在应用程序启动之前切换应用程序环境。REPL 命令就是一个很好的例子。
node ace repl 命令在 console 环境中启动应用程序,但该命令在内部在呈现 REPL 提示符之前将环境切换到 repl。
if (!app.isBooted) {
app.setEnvironment('repl')
}Node 环境
你可以使用 nodeEnvironment 属性访问 Node.js 环境。该值是对 NODE_ENV 环境变量的引用。但是,该值会进一步规范化以保持一致。
import app from '@adonisjs/core/services/app'
console.log(app.nodeEnvironment)| NODE_ENV | 规范化为 |
|---|---|
| dev | development |
| develop | development |
| stage | staging |
| prod | production |
| testing | test |
此外,你可以使用以下属性作为简写来了解当前环境。
inProduction:检查应用程序是否在生产环境中运行。inDev:检查应用程序是否在开发环境中运行。inTest:检查应用程序是否在测试环境中运行。
import app from '@adonisjs/core/services/app'
// 是否在生产环境
app.inProduction
app.nodeEnvironment === 'production'
// 是否在开发环境
app.inDev
app.nodeEnvironment === 'development'
// 是否在测试环境
app.inTest
app.nodeEnvironment === 'test'状态
状态指的是应用程序的当前状态。你可以访问的框架功能在很大程度上取决于应用程序的当前状态。例如,在应用程序处于 booted 状态之前,你无法访问容器绑定或容器服务。
应用程序始终处于以下已知状态之一。
created:这是应用程序的默认状态。initiated:在此状态下,我们解析/验证环境变量并处理adonisrc.ts文件。booted:在此状态下,应用程序服务提供者已注册并启动。ready:ready 状态因环境而异。例如,在web环境中,ready 状态意味着应用程序已准备好接受新的 HTTP 请求。terminated:应用程序已终止,进程将很快退出。在web环境中,应用程序将不接受新的 HTTP 请求。
import app from '@adonisjs/core/services/app'
console.log(app.getState())你也可以使用以下简写属性来了解应用程序是否处于给定状态。
import app from '@adonisjs/core/services/app'
// 应用程序已启动
app.isBooted
app.getState() !== 'created' && app.getState() !== 'initiated'
// 应用程序已就绪
app.isReady
app.getState() === 'ready'
// 正在优雅地尝试终止应用程序
app.isTerminating
// 应用程序已终止
app.isTerminated
app.getState() === 'terminated'监听进程信号
你可以使用 app.listen 或 app.listenOnce 方法监听 POSIX 信号。在底层,我们使用 Node.js process 对象注册监听器。
import app from '@adonisjs/core/services/app'
// 监听 SIGTERM 信号
app.listen('SIGTERM', () => {
})
// 只监听一次 SIGTERM 信号
app.listenOnce('SIGTERM', () => {
})有时,你可能想有条件地注册监听器。例如,在 pm2 环境中运行时监听 SIGINT 信号。
你可以使用 listenIf 或 listenOnceIf 方法有条件地注册监听器。只有当第一个参数的值为真值时才会注册监听器。
import app from '@adonisjs/core/services/app'
app.listenIf(app.managedByPm2, 'SIGTERM', () => {
})
app.listenOnceIf(app.managedByPm2, 'SIGTERM', () => {
})通知父进程
如果你的应用程序作为子进程启动,你可以使用 app.notify 方法向父进程发送消息。在底层,我们使用 process.send 方法。
import app from '@adonisjs/core/services/app'
app.notify('ready')
app.notify({
isReady: true,
port: 3333,
host: 'localhost'
})创建项目文件的 URL 和路径
我们强烈建议使用以下辅助方法,而不是自己构建绝对 URL 或项目文件的路径。
makeURL
makeURL 方法返回项目根目录中给定文件或目录的文件 URL。例如,你可以在导入文件时生成 URL。
import app from '@adonisjs/core/services/app'
const files = [
'./tests/welcome.spec.ts',
'./tests/maths.spec.ts'
]
await Promise.all(files.map((file) => {
return import(app.makeURL(file).href)
}))makePath
makePath 方法返回项目根目录中给定文件或目录的绝对路径。
import app from '@adonisjs/core/services/app'
app.makePath('app/middleware/auth.ts')configPath
返回项目 config 目录中文件的路径。
app.configPath('shield.ts')
// /project_root/config/shield.ts
app.configPath()
// /project_root/configpublicPath
返回项目 public 目录中文件的路径。
app.publicPath('style.css')
// /project_root/public/style.css
app.publicPath()
// /project_root/publicprovidersPath
返回 providers 目录中文件的路径。
app.providersPath('app_provider')
// /project_root/providers/app_provider.ts
app.providersPath()
// /project_root/providersfactoriesPath
返回数据库 factories 目录中文件的路径。
app.factoriesPath('user.ts')
// /project_root/database/factories/user.ts
app.factoriesPath()
// /project_root/database/factoriesmigrationsPath
返回数据库 migrations 目录中文件的路径。
app.migrationsPath('user.ts')
// /project_root/database/migrations/user.ts
app.migrationsPath()
// /project_root/database/migrationsseedersPath
返回数据库 seeders 目录中文件的路径。
app.seedersPath('user.ts')
// /project_root/database/seeders/users.ts
app.seedersPath()
// /project_root/database/seederslanguageFilesPath
返回语言文件目录中文件的路径。
app.languageFilesPath('en/messages.json')
// /project_root/resources/lang/en/messages.json
app.languageFilesPath()
// /project_root/resources/langviewsPath
返回 views 目录中文件的路径。
app.viewsPath('welcome.edge')
// /project_root/resources/views/welcome.edge
app.viewsPath()
// /project_root/resources/viewsstartPath
返回 start 目录中文件的路径。
app.startPath('routes.ts')
// /project_root/start/routes.ts
app.startPath()
// /project_root/starttmpPath
返回项目根目录中 tmp 目录内文件的路径。
app.tmpPath('logs/mail.txt')
// /project_root/tmp/logs/mail.txt
app.tmpPath()
// /project_root/tmphttpControllersPath
返回 HTTP controllers 目录中文件的路径。
app.httpControllersPath('users_controller.ts')
// /project_root/app/controllers/users_controller.ts
app.httpControllersPath()
// /project_root/app/controllersmodelsPath
返回 models 目录中文件的路径。
app.modelsPath('user.ts')
// /project_root/app/models/user.ts
app.modelsPath()
// /project_root/app/modelsservicesPath
返回 services 目录中文件的路径。
app.servicesPath('user.ts')
// /project_root/app/services/user.ts
app.servicesPath()
// /project_root/app/servicesexceptionsPath
返回 exceptions 目录中文件的路径。
app.exceptionsPath('handler.ts')
// /project_root/app/exceptions/handler.ts
app.exceptionsPath()
// /project_root/app/exceptionsmailsPath
返回 mails 目录中文件的路径。
app.mailsPath('verify_email.ts')
// /project_root/app/mails/verify_email.ts
app.mailsPath()
// /project_root/app/mailsmiddlewarePath
返回 middleware 目录中文件的路径。
app.middlewarePath('auth.ts')
// /project_root/app/middleware/auth.ts
app.middlewarePath()
// /project_root/app/middlewarepoliciesPath
返回 policies 目录中文件的路径。
app.policiesPath('posts.ts')
// /project_root/app/polices/posts.ts
app.policiesPath()
// /project_root/app/policesvalidatorsPath
返回 validators 目录中文件的路径。
app.validatorsPath('create_user.ts')
// /project_root/app/validators/create_user.ts
app.validatorsPath()
// /project_root/app/validators/create_user.tscommandsPath
返回 commands 目录中文件的路径。
app.commandsPath('greet.ts')
// /project_root/commands/greet.ts
app.commandsPath()
// /project_root/commandseventsPath
返回 events 目录中文件的路径。
app.eventsPath('user_created.ts')
// /project_root/app/events/user_created.ts
app.eventsPath()
// /project_root/app/eventslistenersPath
返回 listeners 目录中文件的路径。
app.listenersPath('send_invoice.ts')
// /project_root/app/listeners/send_invoice.ts
app.listenersPath()
// /project_root/app/listeners生成器
生成器用于为不同的实体创建类名和文件名。例如,你可以使用 generators.controllerFileName 方法生成控制器的文件名。
import app from '@adonisjs/core/services/app'
app.generators.controllerFileName('user')
// 输出 - users_controller.ts
app.generators.controllerName('user')
// 输出 - UsersController请参考 generators.ts 源代码查看可用生成器列表。
Application (English Version)
The Application class does all the heavy lifting of wiring together an AdonisJS application. You can use this class to know about the environment in which your app is running, get the current state of the application, or make paths to specific directories.
See also: Application lifecycle
Environment
The environment refers to the application runtime environment. The application is always booted in one of the following known environments.
webenvironment refers to the process started for the HTTP server.consoleenvironment refers to the Ace commands except for the REPL command.replenvironment refers to the process started using thenode ace replcommand.Finally, the
testenvironment refers to the process started using thenode ace testcommand.
You can access the application environment using the getEnvironment method.
import app from '@adonisjs/core/services/app'
console.log(app.getEnvironment())You can also switch the application environment before it has been booted. A great example of this is the REPL command.
The node ace repl command starts the application in the console environment, but the command internally switches the environment to repl before presenting the REPL prompt.
if (!app.isBooted) {
app.setEnvironment('repl')
}Node environment
You can access the Node.js environment using the nodeEnvironment property. The value is a reference to the NODE_ENV environment variable. However, the value is further normalized to be consistent.
import app from '@adonisjs/core/services/app'
console.log(app.nodeEnvironment)| NODE_ENV | Normalized to |
|---|---|
| dev | development |
| develop | development |
| stage | staging |
| prod | production |
| testing | test |
Also, you can use the following properties as a shorthand to know the current environment.
inProduction: Check if the application is running in the production environment.inDev: Check if the application is running in the development environment.inTest: Check if the application is running in the test environment.
import app from '@adonisjs/core/services/app'
// Is in production
app.inProduction
app.nodeEnvironment === 'production'
// Is in development
app.inDev
app.nodeEnvironment === 'development'
// Is in the test
app.inTest
app.nodeEnvironment === 'test'State
The state refers to the current state of the application. The framework features you can access significantly depend upon the current state of the application. For example, you cannot access the container bindings or container services until the app is in a booted state.
The application is always in one of the following known states.
created: It is the default state of the application.initiated: In this state, we parse/validate the environment variables and process theadonisrc.tsfile.booted: The application service providers are registered and booted at this state.ready: The ready state varies between different environments. For example, in thewebenvironment, the ready state means the application is ready to accept new HTTP requests.terminated: The application has been terminated, and the process will exit shortly. The application will not accept new HTTP requests in thewebenvironment.
import app from '@adonisjs/core/services/app'
console.log(app.getState())You can also use the following shorthand properties to know whether the application is in a given state.
import app from '@adonisjs/core/services/app'
// App is booted
app.isBooted
app.getState() !== 'created' && app.getState() !== 'initiated'
// App is ready
app.isReady
app.getState() === 'ready'
// gracefully attempting to terminate the app
app.isTerminating
// App has been terminated
app.isTerminated
app.getState() === 'terminated'Listening for process signals
You can listen for POSIX signals using the app.listen, or app.listenOnce methods. Under the hood, we register the listener with the Node.js process object.
import app from '@adonisjs/core/services/app'
// Listen for a SIGTERM signal
app.listen('SIGTERM', () => {
})
// Listen once for a SIGTERM signal
app.listenOnce('SIGTERM', () => {
})At times, you might want to register the listeners conditionally. For example, listen to the SIGINT signal when running inside the pm2 environment.
You can use the listenIf or listenOnceIf methods to register a listener conditionally. The listener is only registered when the first argument's value is truthy.
import app from '@adonisjs/core/services/app'
app.listenIf(app.managedByPm2, 'SIGTERM', () => {
})
app.listenOnceIf(app.managedByPm2, 'SIGTERM', () => {
})Notifying parent process
If your application starts as a child process, you can send messages to the parent process using the app.notify method. Under the hood, we use the process.send method.
import app from '@adonisjs/core/services/app'
app.notify('ready')
app.notify({
isReady: true,
port: 3333,
host: 'localhost'
})Making URLs and paths to project files
Instead of self-constructing absolute URLs or paths to project files, we highly recommend using the following helpers.
makeURL
The make URL method returns a file URL to a given file or directory within the project root. For example, you may generate a URL when importing a file.
import app from '@adonisjs/core/services/app'
const files = [
'./tests/welcome.spec.ts',
'./tests/maths.spec.ts'
]
await Promise.all(files.map((file) => {
return import(app.makeURL(file).href)
}))makePath
The makePath method returns an absolute path to a given file or directory within the project root.
import app from '@adonisjs/core/services/app'
app.makePath('app/middleware/auth.ts')configPath
Returns path to a file inside the project's config directory.
app.configPath('shield.ts')
// /project_root/config/shield.ts
app.configPath()
// /project_root/configpublicPath
Returns path to a file inside the project's public directory.
app.publicPath('style.css')
// /project_root/public/style.css
app.publicPath()
// /project_root/publicprovidersPath
Returns path to a file inside the provider's directory.
app.providersPath('app_provider')
// /project_root/providers/app_provider.ts
app.providersPath()
// /project_root/providersfactoriesPath
Returns path to a file inside the database factories directory.
app.factoriesPath('user.ts')
// /project_root/database/factories/user.ts
app.factoriesPath()
// /project_root/database/factoriesmigrationsPath
Returns path to a file inside the database migrations directory.
app.migrationsPath('user.ts')
// /project_root/database/migrations/user.ts
app.migrationsPath()
// /project_root/database/migrationsseedersPath
Returns path to a file inside the database seeders directory.
app.seedersPath('user.ts')
// /project_root/database/seeders/users.ts
app.seedersPath()
// /project_root/database/seederslanguageFilesPath
Returns path to a file inside languages directory.
app.languageFilesPath('en/messages.json')
// /project_root/resources/lang/en/messages.json
app.languageFilesPath()
// /project_root/resources/langviewsPath
Returns path to a file inside the views directory.
app.viewsPath('welcome.edge')
// /project_root/resources/views/welcome.edge
app.viewsPath()
// /project_root/resources/viewsstartPath
Returns path to a file inside the start directory.
app.startPath('routes.ts')
// /project_root/start/routes.ts
app.startPath()
// /project_root/starttmpPath
Returns path to a file inside the tmp directory within the project root.
app.tmpPath('logs/mail.txt')
// /project_root/tmp/logs/mail.txt
app.tmpPath()
// /project_root/tmphttpControllersPath
Returns path to a file inside the HTTP controllers directory.
app.httpControllersPath('users_controller.ts')
// /project_root/app/controllers/users_controller.ts
app.httpControllersPath()
// /project_root/app/controllersmodelsPath
Returns path to a file inside the model's directory.
app.modelsPath('user.ts')
// /project_root/app/models/user.ts
app.modelsPath()
// /project_root/app/modelsservicesPath
Returns path to a file inside the services directory.
app.servicesPath('user.ts')
// /project_root/app/services/user.ts
app.servicesPath()
// /project_root/app/servicesexceptionsPath
Returns path to a file inside the exceptions directory.
app.exceptionsPath('handler.ts')
// /project_root/app/exceptions/handler.ts
app.exceptionsPath()
// /project_root/app/exceptionsmailsPath
Returns path to a file inside the mails directory.
app.mailsPath('verify_email.ts')
// /project_root/app/mails/verify_email.ts
app.mailsPath()
// /project_root/app/mailsmiddlewarePath
Returns path to a file inside the middleware directory.
app.middlewarePath('auth.ts')
// /project_root/app/middleware/auth.ts
app.middlewarePath()
// /project_root/app/middlewarepoliciesPath
Returns path to a file inside the policies directory.
app.policiesPath('posts.ts')
// /project_root/app/polices/posts.ts
app.policiesPath()
// /project_root/app/policesvalidatorsPath
Returns path to a file inside the validators directory.
app.validatorsPath('create_user.ts')
// /project_root/app/validators/create_user.ts
app.validatorsPath()
// /project_root/app/validators/create_user.tscommandsPath
Returns path to a file inside the commands directory.
app.commandsPath('greet.ts')
// /project_root/commands/greet.ts
app.commandsPath()
// /project_root/commandseventsPath
Return path to a file inside the events directory.
app.eventsPath('user_created.ts')
// /project_root/app/events/user_created.ts
app.eventsPath()
// /project_root/app/eventslistenersPath
Return path to a file inside the listeners directory.
app.listenersPath('send_invoice.ts')
// /project_root/app/listeners/send_invoice.ts
app.listenersPath()
// /project_root/app/listenersGenerators
Generators are used to create class names and file names for different entities. For example, you may use the generators.controllerFileName method to generate the filename for a controller.
import app from '@adonisjs/core/services/app'
app.generators.controllerFileName('user')
// output - users_controller.ts
app.generators.controllerName('user')
// output - UsersControllerPlease reference the generators.ts source code to view the list of available generators.