Laravel 是一个免费的开源的PHP框架,它建立在Symfony 组件之上、提供了使日常开发所用到的诸如认证、路由、sessions和缓存管理的实现变得更加容易的框架。
在这个教程里,我们将看到使用Phpstorm的Laravel插件和Laravel IDE helper来充分利用PhpStorm开发Laravel应用的巨大好处。但是最好还是先了解一下PhpStorm的相关教程和在Laracast上的PhpStorm教程,这些教程可以让你学到更多的关于使用PhpStorm来进行Laravel 和 PHP 开发的知识。
事前准备(插件安装和配置)
PhpStorm 为PHP 提供了代码补全、导航、自动检查、重构等诸多特性。它同时也支持Laravel的模板引擎–Blade。使用Laravel插件和Laravel IDE 助手,我们可以让Phpstorm更好的支持Laravel。下面我们将介绍如何安装这些插件:
开始的时候需要一些初始化的安装工作,不过别担心,这些都是一次性的。完成这些设置工作就可以确保PhpStorm能够对Laravel 提供完全的支持,包括代码补全、导航、Composer支持、Artisan 命令行工具和扩展的Blade语法。
1. 确保Composer初始化
所有工作开始之前,我们必须确保PhpStorm里的Composer已经完成初始化和配置。先打开一个Laravel 项目,然后在project tool 窗口选择根节点、然后右键->Composer | Init composer 。 如果你的电脑里没有composer.phar,可以点击链接来下载。
2. 安装 Laravel IDE 助手
安装好Composer以后,我们就可以开始安装Laravel IDE helper 了。同样我们再项目的根节点上右键,弹出菜单选择 Composer | Add dependency… 然后搜索 barryvdh/laravel-ide-helper. 点击Install 就把这个插件安装到我们的项目里了。
这必须要说明一下,如果在添加packages的时候出现错误,无法下载list.json。需要更新你的JDK到1.8,然后修改/Applications/PhpStorm.app/Contents/Info.plist
JVMVersion 1.6*
变成
JVMVersion 1.8*
这里的修改方法针对mac os 用户有效,至于windows 用户 请自行google。
如果还是有问题,请设法到墙外去。
安装好了以后,我们需要把 Laravel IDE helper 作为 ServiceProvider 添加到项目里. 找到项目的 app/config/app.php file, 在 providers element 下面添加 ‘Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider’, 类似这个样子 :
<?php
return array(
// ...
'providers' => array(
// ...
'Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider', // Laravel IDE helper
),
// ...
);
Laracasts 上有关于添加Laravel IDE Helper的视频教程,可以参考。
3. 使用 Artisan 来生成PHPDoc Helper 文件
装好 Laravel IDE Helper 以后,我们可以用artisan 来生成 PHPDoc helper 文件, PhpStorm 和 Laravel plugin 依据这个文件来完成代码补全和导航的功能。最简单的办法是添加artisan 命令行工具。依次点击 Preferences下的Tools | Command Line Tool Support. 工具类型选择 Tool based on Symfony Console. 接下来填好 artisan 的路径
如果你是windows 用户,应该在setting 下
保存以后,我们就可以在编辑器内部使用artisan命令了,爽吧?菜单下的 Tools | Run Command… menu (快捷键 Ctrl+Shift+X, Mac OS X 下的是 CMD+Shift+X ) ,全部artisan 命令都支持. 运行 artisan ide-helper:generate 命令,就可以生成 PHPDoc 信息了。
提示
在添加了services, controllers, models and views 以后,需要运行Laravel IDE Helper 。 Laravel IDE Helper GitHub 主页上有关于什么时候运行的提示, 举个例子就是在安装或者更新Composer依赖以后,你需要运行一下。另外一个方法是使用 PhpStorm 里的 File Watchers 来自动生成,比如composer.json被更新了。
4. 安装并激活 Laravel Plugin
在 Settings (Preferences) | Plugins 下, 点击 Browse repositories… 按钮然后搜索 Laravel。然后点击安装。
需要重启PhpStorm来完成安装,接下来,是激活的过程,依次是 Settings (Preferences) | Other Settings | Laravel Plugin | Enable Plugin for this Project. 然后还是一次重启过程。
如果现在插件的代码补全和导航有问题,可以通过File | Invalidate Caches / Restart 来重新建立索引。有时候还得使用 artisan clear-compiled 和 artisan ide-helper:generate 这两个命令。
设置到这里基本就结束了,接下来就是见证奇迹的时刻了。
让我们先了解一下Laravel plugin 的特性。
代码自动补全还有Controllers和 Routes的导航。当需要指向一个controller的时候,我们可以使用代码补全功能,快捷键是Ctrl+Space (CMD+Space on Mac OS X) 然后从弹出的列表中选择用到的controller. 这个功能在Redirect 和 Route 里非常常用。
还有两个常用的快捷键,分别是跳转到controller, Ctrl+Click (CMD+Click on Mac OS X) 和 跳转到声明Declaration (Ctrl+B / CMD+B)。按住Ctrl or CMD , 鼠标移动到关键词上就会显示该函数的细节。
视图中的代码补全和导航
使用 View facade, 我们可以引用 Blade 模板 (或者 view). Laravel plugin 提供了视图名的代码补全功能 :
和 controllers 里一样,我们同意可以使用 Ctrl+Click (CMD+Click on Mac OS X) 跳转到视图,或者用 (Ctrl+B / CMD+B) 跳转到声明, PhpStorm 允许我们直接跳转到 Blade template. 按住 Ctrl / CMD 把鼠标移动到关键词上显示更多细节。
配置和服务的代码补全和导航
当使用Configuration facade进行Laravel配置的时候,代码补全功能也是有效的。
同样,针对services也可以完成代码补全。
还是老办法,向导航到配置的入口,可以使用 Ctrl+Click (CMD+Click on Mac OS X) ,跳转到定义用 (Ctrl+B / CMD+B). 按住Ctrl 或者 CMD 然后鼠标悬停,就显示更多细节。如果有多个定义 PhpStorm 允许我们选择我们到底是想导航到哪一个。
至于说 Laravel services 操作方法是一样的。
翻译的代码补全和导航
使用 Lang facade, 我们能得到那些已经被翻译过的字符串。Laravel plugin安装好以后,使用Lang::get() 然后Ctrl+Space (CMD+Space on Mac OS X) 就能选择翻译过的字符串的自动补全。
按住Ctrl 或者 CMD,鼠标悬停,可以看到翻译关键字的定义。用 (Ctrl+B / CMD+B) 跳转到定义。通常一个关键字可能有多个翻译, Laravel plugin 就显示一个文件列表供我们选择。
自动 PSR-4 命名空间
Through the project settings, we can configure the default namespace for various directories in our application, for example for the app directory. Once configured, PhpStorm will follow the PSR-4 standard to automatically namespace new classes created in our application.
From the settings, expand the Project: | Directories node and mark the directory we want to namespace as a Sources directory using the toolbar buttons. Next, click the p icon next to that directory. We can then provide a namespace prefix which is valid for that folder.
PhpStorm > Laravel Development using PhpStorm > psr4-setup.png
When creating new classes under that folder, PhpStorm will automatically provide the namespace for that folder following the PSR-4 standard.
PhpStorm > Laravel Development using PhpStorm > psr4-newclass.png
Read more about PHP Namespaces and PSR Support or watch the Laracasts video on PSR-4 namespacing in PhpStorm.
Blade Template Support in PhpStorm
PhpStorm provides syntax highlighting for Blade templates files. It highlights various Blade syntax constructs, as well as any HTML, JavaScript and CSS code in there.
PhpStorm > Laravel Development using PhpStorm > blade-highlighting.png
Next to syntax highlighting, PhpStorm provides several other Blade-specific functions.
Code Completion for Braces and Directives
PhpStorm’s editor provides code completion for braces, all Blade directives. This includes custom directives, which can be defined in the settings under Languages & Frameworks | PHP | Blade.
PhpStorm > Laravel Development using PhpStorm > blade-directives-completion.png
When @for or @foreach directives are used, variable introduction will be offered with code completion inside the construct’s body.
PhpStorm > Laravel Development using PhpStorm > blade-foreach-variable-completion.png
Sections Support
While working on a Blade template, we can open a section using the @section directive. PhpStorm provides completion (Ctrl+Space / CMD+Space) for all known section names in the project.
PhpStorm > Laravel Development using PhpStorm > section-completion.png
PhpStorm also comes with an automatic code inspection that tells us when we forget to close the section using the @stop directive.
PhpStorm > Laravel Development using PhpStorm > section-inspection.png
We can navigate to where the section is defined using Ctrl+Click (CMD+Click on Mac OS X) or Go To Declaration (Ctrl+B / CMD+B). Simply hovering the mouse with the Ctrl or CMD key pressed tells us we can navigate. The Laravel plugin also adds a marker in the left-hand gutter, which we can also click to navigate to the parent section.
PhpStorm > Laravel Development using PhpStorm > section-marker.png
Sections defined with a @section directive can be collapsed and expanded. Every HTML, JavaScript or CSS block can also be collapsed and expanded
Code Completion and Navigation for Extends and Includes
Blade templates are often composed of various includes of small, reusable blocks which are nothing more than other templates. We can also extend templates and provide content for additional sections. PhpStorm and the Laravel plugin provide completion for template names in both @extends and @include directives. Completion results will include template directory names, as well as full template names which we can select from.
PhpStorm > Laravel Development using PhpStorm > extends-completion.png
We can navigate to the extended or included template using Ctrl+Click (CMD+Click on Mac OS X) or Go To Declaration (Ctrl+B / CMD+B). Hovering the mouse with the Ctrl or CMD key pressed shows us more about where we can navigate. The Laravel plugin also adds a marker in the left-hand gutter, which we can click to navigate to the template.
PhpStorm > Laravel Development using PhpStorm > include-navigation.png
When positioning the cursor on a template name in our Blade code, we can find all usages of that template by invoking Find Usages from the context menu (Alt+F7).
PhpStorm > Laravel Development using PhpStorm > find-usages.png
Generating Code with Live Templates
PhpStorm can generate code for us: complete classes using file templates, or snippets using live templates.
After downloading and installing the PhpStorm Laravel Live Templates, we can extend the standard live templates that are available with a series of Laravel-specific live templates, among which:
Blade directives
Input and Request snippets
Cookie snippets
Route snippets and generation
View, Response and Redirect templates
Building schema (includes column types)
Cache
Form and session snippets
Snippets calling various helpers
Command Line Tool Support for Artisan and Composer
Laravel comes with a command line tool that can be used to perform a variety of tasks such as clearing caches, generating code, migrating database schemas and so on. PhpStorm comes with excellent support for working with artisan: it provides completion for all commands that artisan exposes and validates the arguments passed in. We also do not have to leave our IDE to invoke artisan commands.
Adding command line tool for Composer works in a similar way as adding support for artisan. Check the Composer Support in PhpStorm tutorial for more information.
From the settings, we can add a new command line tool under Tools | Command Line Tool Support. The tool type is a Tool based on Symfony Console. Next, we have to provide the path to artisan which typically is available in our project already:
PhpStorm > Laravel Development using PhpStorm > artisan-command-line-tool.png
PhpStorm will scan all commands exposed by artisan, including those of custom service providers we add to our project.
If a newly added service provider’s commands are not available, open the settings and click the refresh button under Tools | Command Line Tool Support. This will re-index the commands provided by artisan.
Use the Tools | Run Command… menu (Ctrl+Shift+X or CMD+Shift+X on Mac OS X) to open the command line tools console, which now knows artisan and its various commands that are available.
PhpStorm > Laravel Development using PhpStorm > artisan-command-line-tool-completion.png
Jeffrey Way has created a Composer package that adds various Laravel generators for models, views, controllers and much more. Do give these a try as they really speed up the development process.
Debugging Laravel Applications with PhpStorm
Many developers use tricks like printing variables to the output using var_dump or Laravel’s own dd to get information about a variable’s state and our application’s execution. PhpStorm comes with debugging support based on Xdebug and Zend Debugger to make it possible to inspect variables in real-time and step through code while it executes.
After installing Xdebug or Zend Profiler into our PHP runtime, we have to listen for incoming debugger connections. Use the Start Listen for PHP Debug Connections button on the toolbar or the Run | Start Listen for PHP Debug Connections menu. Next, use the PhpStorm Debugger bookmarklets or one of the Browser Debugging Extensions to start debugging. When a breakpoint is hit, PhpStorm will pause execution and lets us inspect variables, the call stack, modify variables at runtime and step through code.
PhpStorm > Laravel Development using PhpStorm > debugging-laravel-with-phpstorm.png
More information about debugging PHP code with PhpStorm is available in our Debugging PHP Applications and Zero-configuration Web Application Debugging with Xdebug and PhpStorm tutorials.
Laracasts also has a video about debugging Laravel applications with PhpStorm that demonstrates a debugging workflow.
Laravel Unit Testing with PhpStorm
With unit testing, we can verify parts of our source code are working as expected. After we’ve changed our code or performed a refactoring, unit tests can tell us if the changes we did break existing functionality or not. Only when all the tests are “green” (all tests pass) can we be sure that we’re not breaking the functionality of our code. Tests for Laravel can be written and executed using PhpStorm’s PHPUnit test runner integration.
Test skeletons can be generated from our code by creating a new file using the PHPUnit | PHPUnit test file template. From within a specific class, we can also use the Go to Test action (with Navigate | Go to Test or Ctrl+Shift+T / CMD+Shift+T) and create a new test. Check our Creating PHPUnit Tests in PhpStorm tutorial for more information about creating PHPUnit tests in PhpStorm.
To run existing tests in a Laravel project, open the project tool window and use the Run | tests context menu on the tests folder. This will create a PHPUnit run configuration and run tests in PhpStorm. This requires PHPUnit support in PhpStorm to be configured, which is done automatically if the Laravel project is based on any of the official Laravel Composer packages like laravel/laravel or laravel/framework.
PhpStorm > Laravel Development using PhpStorm > unit-test-results.png
Checkout the testing in PhpStorm video from Laracasts to see unit testing in action.
Database Support in PhpStorm
Laravel projects are typically backed by a database, which we can manage from within PhpStorm. The IDE can help us perform all types of routine database tasks, such as querying for a record; checking what that column was named again; database development where we have to create the schema structure and more. PhpStorm also provides code completion on table names and columns, while writing PHP code!
We can setup a new database connection from the View | Tool Windows menu. Open the Database tool window and use the green + icon in the toolbar to create a new data source. We can pick the database type we’re using with our application, for example Data Source | SQLite after which PhpStorm will ask us for connection information. Here’s an example configuration:
PhpStorm > Laravel Development using PhpStorm > database-settings.png
PhpStorm does not ship with database drivers installed, but it does provide a handy way of downloading them when needed: click the “Download … driver files” link next to the warning about missing drivers to download them.
After testing and saving the database connection details, we can explore, manage, refactor, query and code against our database. There’s code completion for tables, columns and even for generating JOIN conditions!
PhpStorm > Laravel Development using PhpStorm > database-query-code-completion.png