1. 程式人生 > >優雅的使用 PhpStorm 來開發 Laravel 專案(翻譯中)

優雅的使用 PhpStorm 來開發 Laravel 專案(翻譯中)

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