翻译进度
12
分块数量
1
参与人数

Valet

这是一篇协同翻译的文章,你可以点击『我来翻译』按钮来参与翻译。


Laravel Valet

简介

[!NOTE]
想要在 macOS 或 Windows 上使用更简单的方式开发 Laravel 应用? 可以看看 Laravel Herd. Herd 集成了 Laravel 开发所需的一切,包括 Valet、PHP 和 Composer。

Laravel Valet 是一个为 macOS 极简主义者打造的开发环境。 Valet 会配置你的 Mac,使其在开机时始终在后台运行 Nginx 。 接着,Valet 使用 DnsMasq, 将所有 *.test 域名的请求代理到你本地安装的站点。

换句话说,Valet 是一个极其快速的 Laravel 开发环境,内存占用仅约 7 MB。 它不是 SailHomestead 的完全替代品, 但如果你希望拥有灵活的基础配置、追求极致速度,或使用的是内存有限的设备,那么 Valet 是一个很棒的选择。

Valet 开箱即支持以下(但不限于)框架和系统:

arunfung 翻译于 5天前

不过,你也可以通过 自定义驱动 来扩展 Valet 的功能。

安装

[!WARNING]
Valet 只能运行在 macOS 上,并依赖 Homebrew。 在安装之前,请确保没有其他程序(如 Apache 或 Nginx)占用了本机的 80 端口。

在开始之前,请使用以下命令确保 Homebrew 是最新的:

brew update

接着,通过 Homebrew 安装 PHP:

brew install php

安装完 PHP 后,就可以安装 Composer 包管理器。 另外,请确保你的系统环境变量 "PATH" 中包含目录 $HOME/.composer/vendor/bin 。 Composer 安装完成后,就可以使用以下命令全局安装 Laravel Valet:

composer global require laravel/valet

运行以下命令,Valet 会自动配置并安装自身以及 DnsMasq。 除此之外,Valet 依赖的守护进程也会被配置为随系统启动自动运行:

valet install

安装完成后,你可以尝试在终端中使用 ping foobar.test 来测试任意 *.test 结尾的域名。如果安装正确,该域名应该会返回 127.0.0.1 的响应。

Valet 会在每次开机时自动启动所需的服务。

PHP 版本管理

[!NOTE]
与其修改全局 PHP 版本,不如使用 Valet 的 isolate 命令 为每个站点指定 PHP 版本。

Valet 允许你通过以下命令切换 PHP 版本。如果指定版本尚未安装,Valet 会使用 Homebrew 自动安装:

valet use php@8.2

valet use php
arunfung 翻译于 5天前

你也可以在项目根目录创建一个 .valetrc 文件。该文件应包含该站点所需使用的 PHP 版本,例如:

php=php@8.2

一旦创建好此文件,你只需执行 valet use 命令,Valet 会读取 .valetrc 文件,自动确定该站点所需的 PHP 版本。

[!WARNING]
即使你安装了多个 PHP 版本,Valet 仍然一次只能运行一个 PHP 版本。

数据库

如果你的应用需要数据库,可以试试 DBngin, 它是一个免费的、集成的数据库管理工具,支持 MySQL、PostgreSQL 和 Redis。安装 DBngin 后,你可以使用 127.0.0.1 地址连接数据库,用户名为 root,密码为空。

重置 Valet 安装

如果你在使用 Valet 的过程中遇到问题,可以尝试先执行:composer global require laravel/valet 然后再次运行: valet install 这将重置你的安装环境,通常能解决很多问题。 在少数情况下,你可能需要进行 "强制重置", 使用以下命令: valet uninstall --forcevalet install.

升级 Valet

你可以使用以下命令来更新你的 Valet 安装: composer global require laravel/valet 。 升级完成后,建议再次运行: valet install 命令以便 Valet 在有需要时自动更新配置文件。

升级到 Valet 4

如果你正在从 Valet 3 升级到 Valet 4,请按照以下步骤正确进行升级:

  • 如果你之前使用 .valetphprc 文件为站点设置 PHP 版本, 请将其重命名为 .valetrc。并在文件内容前添加 php= 前缀。
  • 如果你使用了自定义驱动,请更新命名空间、类扩展、类型提示和返回类型提示,以符合新的驱动系统规范。你可以参考 Valet 的 示例驱动 SampleValetDriver
  • 如果你使用 PHP 7.1 到 7.4 来服务站点,请确保仍通过 Homebrew 安装一个 PHP 8.0 或以上的版本。即使该版本不是你的主版本,Valet 的某些脚本也会依赖该版本运行。
arunfung 翻译于 5天前

服务站点

当你完成 Valet 的安装后,就可以开始运行你的 Laravel 应用了。Valet 提供了两个命令来帮助你服务本地应用:parklink.

park 命令

park 命令用于注册一个包含多个项目的目录。 一旦你将某个目录通过 park 命令注册到 Valet, 该目录下的每一个子目录都可以通过浏览器访问,形式为 http://<directory-name>.test:

cd ~/Sites

valet park

就是这么简单。现在你在这个 "parked" 目录中创建的任何应用,都可以通过 http://<directory-name>.test 来访问。例如, i如果该目录下有一个名为 "laravel" 的子目录, 该目录中的应用就可以通过 http://laravel.test 访问。 此外,Valet 还自动支持通配子域名,例如: (http://foo.laravel.test) 也可以正常访问。

link 命令

link 命令也可以用来服务 Laravel 应用。当你只想单独服务某一个项目目录,而不是整个目录时,link 是一个更合适的选择:

cd ~/Sites/laravel

valet link

一旦你使用 link 命令将该项目链接到 Valet,就可以通过其目录名访问它。例如,上面的项目将可以通过 http://laravel.test访问。 同样地,Valet 也支持该站点的通配子域名访问,如: (http://foo.laravel.test).

如果你希望用另一个自定义的域名来访问这个站点,可以在 link 命令中指定域名,例如,以下命令会让该应用可以通过 http://application.test访问。

cd ~/Sites/laravel

valet link application
arunfung 翻译于 5天前

当然,你也可以使用 link 命令将应用配置为子域名的形式:

valet link api.application

你可以使用 links 命令查看所有已链接的目录列表:

valet links

要删除某个站点的符号链接,可以使用 unlink 命令:

cd ~/Sites/laravel

valet unlink

使用 TLS 加密站点

默认情况下,Valet 是通过 HTTP 提供站点服务。但如果你希望通过 加密的 TLS(支持 HTTP/2) 来访问站点,可以使用 secure 命令。 例如,如果你的站点域名为 laravel.test, 你可以运行以下命令来启用 HTTPS:

valet secure laravel

若你希望取消加密访问(即恢复为普通 HTTP),可以使用 unsecure 命令。该命令与 secure 相似,需要指定要取消加密的站点:

valet unsecure laravel

设置默认站点

有时,你可能希望在访问未知的 test 域名时不返回 404 页面,而是跳转到一个 "默认" 站点。 你可以在配置文件 ~/.config/valet/config.json 中添加一个 default 选项,配置默认站点路径,例如:

"default": "/Users/Sally/Sites/example-site",

按站点指定 PHP 版本

默认情况下,Valet 使用你系统中全局安装的 PHP 版本来运行站点。但如果你需要在不同的站点中使用不同版本的 PHP,可以使用 isolate 命令为特定站点指定 PHP 版本。 isolate 命令会将当前目录下的站点配置为使用指定的 PHP 版本:

cd ~/Sites/example-site

valet isolate php@8.0
arunfung 翻译于 5天前

If your site name does not match the name of the directory that contains it, you may specify the site name using the --site option:

valet isolate php@8.0 --site="site-name"

For convenience, you may use the valet php, composer, and which-php commands to proxy calls to the appropriate PHP CLI or tool based on the site's configured PHP version:

valet php
valet composer
valet which-php

You may execute the isolated command to display a list of all of your isolated sites and their PHP versions:

valet isolated

To revert a site back to Valet's globally installed PHP version, you may invoke the unisolate command from the site's root directory:

valet unisolate

Sharing Sites

Valet includes a command to share your local sites with the world, providing an easy way to test your site on mobile devices or share it with team members and clients.

Out of the box, Valet supports sharing your sites via ngrok or Expose. Before sharing a site, you should update your Valet configuration using the share-tool command, specifying ngrok, expose, or cloudflared:

valet share-tool ngrok

If you choose a tool and don't have it installed via Homebrew (for ngrok and cloudflared) or Composer (for Expose), Valet will automatically prompt you to install it. Of course, both tools require you to authenticate your ngrok or Expose account before you can start sharing sites.

To share a site, navigate to the site's directory in your terminal and run Valet's share command. A publicly accessible URL will be placed into your clipboard and is ready to paste directly into your browser or to be shared with your team:

cd ~/Sites/laravel

valet share

To stop sharing your site, you may press Control + C.

[!WARNING]
If you're using a custom DNS server (like 1.1.1.1), ngrok sharing may not work correctly. If this is the case on your machine, open your Mac's system settings, go to the Network settings, open the Advanced settings, then go the DNS tab and add 127.0.0.1 as your first DNS server.

Sharing Sites via Ngrok

Sharing your site using ngrok requires you to create an ngrok account and set up an authentication token. Once you have an authentication token, you can update your Valet configuration with that token:

valet set-ngrok-token YOUR_TOKEN_HERE

[!NOTE]
You may pass additional ngrok parameters to the share command, such as valet share --region=eu. For more information, consult the ngrok documentation.

Sharing Sites via Expose

Sharing your site using Expose requires you to create an Expose account and authenticate with Expose via your authentication token.

You may consult the Expose documentation for information regarding the additional command-line parameters it supports.

Sharing Sites on Your Local Network

Valet restricts incoming traffic to the internal 127.0.0.1 interface by default so that your development machine isn't exposed to security risks from the Internet.

If you wish to allow other devices on your local network to access the Valet sites on your machine via your machine's IP address (eg: 192.168.1.10/application.test), you will need to manually edit the appropriate Nginx configuration file for that site to remove the restriction on the listen directive. You should remove the 127.0.0.1: prefix on the listen directive for ports 80 and 443.

If you have not run valet secure on the project, you can open up network access for all non-HTTPS sites by editing the /usr/local/etc/nginx/valet/valet.conf file. However, if you're serving the project site over HTTPS (you have run valet secure for the site) then you should edit the ~/.config/valet/Nginx/app-name.test file.

Once you have updated your Nginx configuration, run the valet restart command to apply the configuration changes.

Site Specific Environment Variables

Some applications using other frameworks may depend on server environment variables but do not provide a way for those variables to be configured within your project. Valet allows you to configure site specific environment variables by adding a .valet-env.php file within the root of your project. This file should return an array of site / environment variable pairs which will be added to the global $_SERVER array for each site specified in the array:

<?php

return [
    // Set $_SERVER['key'] to "value" for the laravel.test site...
    'laravel' => [
        'key' => 'value',
    ],

    // Set $_SERVER['key'] to "value" for all sites...
    '*' => [
        'key' => 'value',
    ],
];

Proxying Services

Sometimes you may wish to proxy a Valet domain to another service on your local machine. For example, you may occasionally need to run Valet while also running a separate site in Docker; however, Valet and Docker can't both bind to port 80 at the same time.

To solve this, you may use the proxy command to generate a proxy. For example, you may proxy all traffic from http://elasticsearch.test to http://127.0.0.1:9200:

# Proxy over HTTP...
valet proxy elasticsearch http://127.0.0.1:9200

# Proxy over TLS + HTTP/2...
valet proxy elasticsearch http://127.0.0.1:9200 --secure

You may remove a proxy using the unproxy command:

valet unproxy elasticsearch

You may use the proxies command to list all site configurations that are proxied:

valet proxies

Custom Valet Drivers

You can write your own Valet "driver" to serve PHP applications running on a framework or CMS that is not natively supported by Valet. When you install Valet, a ~/.config/valet/Drivers directory is created which contains a SampleValetDriver.php file. This file contains a sample driver implementation to demonstrate how to write a custom driver. Writing a driver only requires you to implement three methods: serves, isStaticFile, and frontControllerPath.

All three methods receive the $sitePath, $siteName, and $uri values as their arguments. The $sitePath is the fully qualified path to the site being served on your machine, such as /Users/Lisa/Sites/my-project. The $siteName is the "host" / "site name" portion of the domain (my-project). The $uri is the incoming request URI (/foo/bar).

Once you have completed your custom Valet driver, place it in the ~/.config/valet/Drivers directory using the FrameworkValetDriver.php naming convention. For example, if you are writing a custom valet driver for WordPress, your filename should be WordPressValetDriver.php.

Let's take a look at a sample implementation of each method your custom Valet driver should implement.

The serves Method

The serves method should return true if your driver should handle the incoming request. Otherwise, the method should return false. So, within this method, you should attempt to determine if the given $sitePath contains a project of the type you are trying to serve.

For example, let's imagine we are writing a WordPressValetDriver. Our serves method might look something like this:

/**
 * Determine if the driver serves the request.
 */
public function serves(string $sitePath, string $siteName, string $uri): bool
{
    return is_dir($sitePath.'/wp-admin');
}

The isStaticFile Method

The isStaticFile should determine if the incoming request is for a file that is "static", such as an image or a stylesheet. If the file is static, the method should return the fully qualified path to the static file on disk. If the incoming request is not for a static file, the method should return false:

/**
 * Determine if the incoming request is for a static file.
 *
 * @return string|false
 */
public function isStaticFile(string $sitePath, string $siteName, string $uri)
{
    if (file_exists($staticFilePath = $sitePath.'/public/'.$uri)) {
        return $staticFilePath;
    }

    return false;
}

[!WARNING]
The isStaticFile method will only be called if the serves method returns true for the incoming request and the request URI is not /.

The frontControllerPath Method

The frontControllerPath method should return the fully qualified path to your application's "front controller", which is typically an "index.php" file or equivalent:

/**
 * Get the fully resolved path to the application's front controller.
 */
public function frontControllerPath(string $sitePath, string $siteName, string $uri): string
{
    return $sitePath.'/public/index.php';
}

Local Drivers

If you would like to define a custom Valet driver for a single application, create a LocalValetDriver.php file in the application's root directory. Your custom driver may extend the base ValetDriver class or extend an existing application specific driver such as the LaravelValetDriver:

use Valet\Drivers\LaravelValetDriver;

class LocalValetDriver extends LaravelValetDriver
{
    /**
     * Determine if the driver serves the request.
     */
    public function serves(string $sitePath, string $siteName, string $uri): bool
    {
        return true;
    }

    /**
     * Get the fully resolved path to the application's front controller.
     */
    public function frontControllerPath(string $sitePath, string $siteName, string $uri): string
    {
        return $sitePath.'/public_html/index.php';
    }
}

Other Valet Commands

| Command | Description | | --- | --- | | `valet list` | Display a list of all Valet commands. | | `valet diagnose` | Output diagnostics to aid in debugging Valet. | | `valet directory-listing` | Determine directory-listing behavior. Default is "off", which renders a 404 page for directories. | | `valet forget` | Run this command from a "parked" directory to remove it from the parked directory list. | | `valet log` | View a list of logs which are written by Valet's services. | | `valet paths` | View all of your "parked" paths. | | `valet restart` | Restart the Valet daemons. | | `valet start` | Start the Valet daemons. | | `valet stop` | Stop the Valet daemons. | | `valet trust` | Add sudoers files for Brew and Valet to allow Valet commands to be run without prompting for your password. | | `valet uninstall` | Uninstall Valet: shows instructions for manual uninstall. Pass the `--force` option to aggressively delete all of Valet's resources. |

Valet Directories and Files

You may find the following directory and file information helpful while troubleshooting issues with your Valet environment:

~/.config/valet

Contains all of Valet's configuration. You may wish to maintain a backup of this directory.

~/.config/valet/dnsmasq.d/

This directory contains DNSMasq's configuration.

~/.config/valet/Drivers/

This directory contains Valet's drivers. Drivers determine how a particular framework / CMS is served.

~/.config/valet/Nginx/

This directory contains all of Valet's Nginx site configurations. These files are rebuilt when running the install and secure commands.

~/.config/valet/Sites/

This directory contains all of the symbolic links for your linked projects.

~/.config/valet/config.json

This file is Valet's master configuration file.

~/.config/valet/valet.sock

This file is the PHP-FPM socket used by Valet's Nginx installation. This will only exist if PHP is running properly.

~/.config/valet/Log/fpm-php.www.log

This file is the user log for PHP errors.

~/.config/valet/Log/nginx-error.log

This file is the user log for Nginx errors.

/usr/local/var/log/php-fpm.log

This file is the system log for PHP-FPM errors.

/usr/local/var/log/nginx

This directory contains the Nginx access and error logs.

/usr/local/etc/php/X.X/conf.d

This directory contains the *.ini files for various PHP configuration settings.

/usr/local/etc/php/X.X/php-fpm.d/valet-fpm.conf

This file is the PHP-FPM pool configuration file.

~/.composer/vendor/laravel/valet/cli/stubs/secure.valet.conf

This file is the default Nginx configuration used for building SSL certificates for your sites.

Disk Access

Since macOS 10.14, access to some files and directories is restricted by default. These restrictions include the Desktop, Documents, and Downloads directories. In addition, network volume and removable volume access is restricted. Therefore, Valet recommends your site folders are located outside of these protected locations.

However, if you wish to serve sites from within one of those locations, you will need to give Nginx "Full Disk Access". Otherwise, you may encounter server errors or other unpredictable behavior from Nginx, especially when serving static assets. Typically, macOS will automatically prompt you to grant Nginx full access to these locations. Or, you may do so manually via System Preferences > Security & Privacy > Privacy and selecting Full Disk Access. Next, enable any nginx entries in the main window pane.

本文章首发在 LearnKu.com 网站上。

本文中的所有译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。

《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
贡献者:1
讨论数量: 1
发起讨论 只看当前版本


newbmiao
为何没有推荐使用 laradock 作为 Laravel 开发环境?
0 个点赞 | 11 个回复 | 问答 | 课程版本 5.8