PHP教學使用Laravel UP&Running

15219530_10153907201561541_2832799405435708129_n 15078697_10153881834396541_6056991165676200917_n
這學期教產業學院,捨去了CodeIgniter框架,而改用Laravel。也因為想找一本適合學生的課本,找了目前繁體/簡體書~但仍沒有好的教材。幸好最近看到了 Laravel Up&Running 這本書,就直接買下電子版苦讀一番,這週開始就開始以這本書為藍圖來做教學。希望能讓台灣的PHP教學環境更進步 🙂

【本文同步於CodeData】PHP Laravel 開發入門(四) – 路由(Routes)

任何一個網站框架最基本的功能就是透過http(s)取得客戶端的需求後並且回覆相關資訊,這意味著在學習框架中首要的是定義路由,如果沒有路由也就無法完成與客戶端互動。
在本章我們將瞭解Laravel的框架以及如何定義路由,並且熟悉如何使用Laravel的路由工具去處理各種路由的需求。

在Laravel的框架中,你可以透過 routes/web.php 定義 web相關的 routes,並透過 routes/api.php 定義 api相關的 routes。也就是說你可以將api與web做區隔建立對應的route。(如果是 5.3之前的版本,routes則存在 app/Http/routes.php中。)在這邊我們主要討論的是 web.php為主。

基本路由

在web.php中有一個為根目錄(‘/’)且附帶閉包函數的預設路由。這個路由預設是使用者造訪根目錄時,就會回傳 welcome.blade.php 的內容。

1
2
3
Route::get('/', function () {
return view('welcome');
});

除此之外,我們也可以不透過echo或print回傳字串。例如:

1
2
3
Route::get('/', function () {
return 'Hello World!';
});

假設我們要設定一個回傳about的路由,可以透過

1
2
3
Route::get('about', function () {
return 'this is about!';
});

或顯示 resource/views/about.blade.php

1
2
3
Route::get('about', function () {
return view('about');
});

路由動詞

在HTTP通訊協定中制定了幾種動詞(Verbs)與伺服器溝通,在上一節中我們使用GET用來讀取資料。那其他PUT、POST、DELETE該如何定義?

1
2
3
4
5
Route::post('/', function () {});
Route::put('/', function () {});
Route::delete('/', function () {});

如果要符合所有通詞,則使用any

1
Route::any('/', function () {});

另外,要符合部分動詞,則使用match

1
Route::match(['get', 'post'], '/', function () {});

如果要路由至特定的控制器(Controller),下面的例子會對應到 app/Http/Controllers/WelcomeController.php的index函數

1
Route::get('/', 'WelcomeController@index');

路由參數

如果你的路由需要傳遞參數的話,,該如何傳遞呢?

1
2
3
Route::get('users/{id}', function ($id) {
//
});

如果傳遞的參數要有預設值的話,

1
2
3
Route::get('users/{id}', function ($id='123') {
//
});

另外,參數也可以透過正規式讓裡頭的函數只能接收相 對應的值。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// id只能輸入 0-9
Route::get('users/{id}', function ($id) {
//
})->where('id', '[0-9]+');
// username只能輸入大小寫的英文字母
Route::get('users/{username}', function ($username) {
//
})->where('username', '[A-Za-z]+');
// id只能輸入數字;slug只能輸入英文字母
Route::get('posts/{id}/{slug}', function ($id, $slug) {
Route Definitions | 27
//
})->where(['id' => '[0-9]+', 'slug' => '[A-Za-z]+']);

路由命名

在url Helper可以透過 url()去轉向,而在laravel框架中更允許你對每個路由做命名。

例如我們要顯示某一位會員的資料,可以先將會員資料做處理,

1
2
3
4
// 定義members/ID為members.show
Route::get('members/{id}', 'MembersController@show')->name('members.show');
// 在View
<a href="<?php echo route('members.show', ['id' => 14]); ?>">

路由群組

在Laravel裡有一個好用的路由群組,舉例來說,我有一個api相關的群組,一開始的定義可能如下:

1
2
3
4
5
6
Route::get('/api', function () {
});
Route::get('/api/users', function () {
});

我們透過路由群組可以簡化成

1
2
3
4
5
6
7
8
Route::group(['prefix' => 'api'], function () {
Route::get('/', function () {
});
Route::get('users', function () {
});
});

子網域路由

在網址裡,可能會有不同的子網域,我們也可以透過子網域的路由來完成

1
2
3
4
5
Route::group(['domain' => 'admin.codedata.com.tw'], function () {
Route::get('/', function () {
//
});
});

同樣的,也可以透過參數帶入不同的子網域

1
2
3
4
5
6
7
Route::group(['domain' => '{account}.codedata.com.tw'], function () {
Route::get('/', function ($account) {
//
});
Route::get('article/{id}', function ($account, $id) {
//
});

這樣大家對路由有沒有基本的瞭解了呢?下一次我們來解說Controller(控制器)。

PhpStorm 2016.3版本釋出了!


PhpStorm是目前PHP開發工具中最強也最完整的一套,11/24推出2016.3的正式版本了!

  • 工具和框架:在遠程解釋程序中支持 Docker、支持 PHPSpec 測試框架、自動檢測和配置 PHPUnit、Behat 和 composer.json 內的 PHPSpec、在一個框架中打開多個項目,以及支持 Codeigniter 代碼風格。
  • 新的編輯體驗:語意突顯變量和參數、無需函數和 var 關鍵字即可完成重載方法和屬性,以及改進對 PSR-0/PSR-4 的支持。
  • 代碼質量分析:項目範圍的 PHP 7 嚴格類型、新的命名約定檢查,並改進運行時錯誤預防。

該版本還對頂尖 web 技術的支持進行了重大改進,如:支持流(flow)、改進對 TypeScript 的支持、支持 PostCSS、Stylelint 等。

原始連結: https://blog.jetbrains.com/phpstorm/2016/11/phpstorm-2016-3-is-now-released/

下載: https://www.jetbrains.com/phpstorm/download/#section=windows-versionphpstorm_debugging2x

Laravel 5.3 連接 SQL Server

一、下載 https://github.com/superlevin/xamppforlaravel

二、config/database.ph的connections增加
[php]
‘sqlsrv’ => [
‘driver’ => ‘sqlsrv’,
‘host’ => env(‘DB_HOST’, ‘localhost’),
‘database’ => env(‘DB_DATABASE’, ‘dbname’),
‘username’ => env(‘DB_USERNAME’, ‘dbuser’),
‘password’ => env(‘DB_PASSWORD’, ‘dbpassword’),
‘charset’ => ‘utf8’,
‘prefix’ => ”,
],
[/php]
三、.env修改連線
[php]
DB_CONNECTION=sqlsrv
DB_HOST=localhost
DB_PORT=1433
DB_DATABASE=dbname
DB_USERNAME=dbuser
DB_PASSWORD=dbpassword
[/php]
四、測試是否可以產生
routes/web.php
[php]
Route::get(‘/’, function () {
var_dump( DB::table(‘tablename’)->first() );
});
[/php]

Laravel 5.3 Artisan 自動建立CRUD的Controller

在5.2之前,是使用以上指令產生有resource(CRUD函數的controller)
[php]
php artisan make:controller MyNameController
[/php]
然後
[php]
php artisan make:controller MyNameController –plain
[/php]
在5.3,改為要加上 –resource才有
[php]
php artisan make:controller MyNameController –resource
[/php]

PHP教學 – 這學期教的laravel 5.3課程內容

上個學期是教Codeigniter,這學期開始也要進入Laravel了!內容大致如下面~
Laravel介紹
MVC架構解說
Git版本控制介紹與安裝
Composer套件管理

Laravel安裝

Package安裝及使用
Route路由
Migrations/Seed 資料的遷移與填充

Eloquent ORM資料庫互動

View與Blade模板引擎
Controller實戰

CRUD 綜合運用

表單與驗證技巧
會員認證
網站安全性

Windows安裝Xampp、Composer、laravel

1.安裝Composer
https://getcomposer.org/
Windows版本直接下載
2.下載XAMPP(解壓縮版),解壓縮到D:\xampp
XAMPP
XAMPP直接下載
3.新增PHP到系統變數

set PATH=%PATH%;d:\xampp\php

另外修改:

extension_dir = “d:\xampp\php\ext”

browscap = “d:\xampp\php\extras\browscap.ini”

4.更新Composer版本

D:\xampp\php>php.exe c:\programdata\composersetup\bin\composer.phar self-update

5.在xampp裡建立一個新的專案叫laraveltest
D:\xampp\htdocs>composer create-project laravel/laravel laraveltest

D:\xampp\htdocs>composer create-project laravel/laravel laraveltest
Installing laravel/laravel (v5.2.0)
– Installing laravel/laravel (v5.2.0)
Downloading: 100%

Created project in laraveltest
> php -r “copy(‘.env.example’, ‘.env’);”
Loading composer repositories with package information
Installing dependencies (including require-dev)
– Installing vlucas/phpdotenv (v2.2.0)
Downloading: 100%

– Installing symfony/polyfill-mbstring (v1.1.0)
Downloading: 100%

– Installing symfony/var-dumper (v3.0.2)
Downloading: 100%

– Installing symfony/translation (v3.0.2)
Downloading: 100%

– Installing symfony/routing (v3.0.2)
Downloading: 100%

– Installing symfony/process (v3.0.2)
Downloading: 100%

– Installing symfony/polyfill-util (v1.1.0)
Downloading: 100%

– Installing symfony/polyfill-php56 (v1.1.0)
Downloading: 100%

– Installing psr/log (1.0.0)
Downloading: 100%

– Installing symfony/debug (v3.0.2)
Downloading: 100%

– Installing symfony/http-foundation (v3.0.2)
Downloading: 100%

– Installing symfony/event-dispatcher (v3.0.2)
Downloading: 100%

– Installing symfony/http-kernel (v3.0.2)
Downloading: 100%

– Installing symfony/finder (v3.0.2)
Downloading: 100%

– Installing symfony/console (v3.0.2)
Downloading: 100%

– Installing swiftmailer/swiftmailer (v5.4.1)
Downloading: 100%

– Installing jakub-onderka/php-console-color (0.1)
Downloading: 100%

– Installing jakub-onderka/php-console-highlighter (v0.3.2)
Downloading: 100%

– Installing dnoegel/php-xdg-base-dir (0.1)
Downloading: 100%

– Installing nikic/php-parser (v2.0.0)
Downloading: 100%

– Installing psy/psysh (v0.6.1)
Downloading: 100%

– Installing paragonie/random_compat (v1.2.0)
Downloading: 100%

– Installing nesbot/carbon (1.21.0)
Downloading: 100%

– Installing mtdowling/cron-expression (v1.1.0)
Downloading: 100%

– Installing monolog/monolog (1.17.2)
Downloading: 100%

– Installing league/flysystem (1.0.16)
Downloading: 100%

– Installing jeremeamia/superclosure (2.2.0)
Downloading: 100%

– Installing doctrine/inflector (v1.1.0)
Downloading: 100%

– Installing classpreloader/classpreloader (3.0.0)
Downloading: 100%

– Installing laravel/framework (v5.2.14)
Downloading: 100%

– Installing fzaninotto/faker (v1.5.0)
Downloading: 100%

– Installing hamcrest/hamcrest-php (v1.2.2)
Downloading: 100%

– Installing mockery/mockery (0.9.4)
Downloading: 100%

– Installing sebastian/version (1.0.6)
Downloading: 100%

– Installing sebastian/global-state (1.1.1)
Downloading: 100%

– Installing sebastian/recursion-context (1.0.2)
Downloading: 100%

– Installing sebastian/exporter (1.2.1)
Downloading: 100%

– Installing sebastian/environment (1.3.3)
Downloading: 100%

– Installing sebastian/diff (1.4.1)
Downloading: 100%

– Installing sebastian/comparator (1.2.0)
Downloading: 100%

– Installing symfony/yaml (v3.0.2)
Downloading: 100%

– Installing doctrine/instantiator (1.0.5)
Downloading: 100%

– Installing phpdocumentor/reflection-docblock (2.0.4)
Downloading: 100%

– Installing phpspec/prophecy (v1.5.0)
Downloading: 100%

– Installing phpunit/php-text-template (1.2.1)
Downloading: 100%

– Installing phpunit/phpunit-mock-objects (2.3.8)
Downloading: 100%

– Installing phpunit/php-timer (1.0.7)
Downloading: 100%

– Installing phpunit/php-token-stream (1.4.8)
Downloading: 100%

– Installing phpunit/php-file-iterator (1.4.1)
Downloading: 100%

– Installing phpunit/php-code-coverage (2.2.4)
Downloading: 100%

– Installing phpunit/phpunit (4.8.23)
Downloading: 100%

– Installing symfony/css-selector (v3.0.2)
Downloading: 100%

– Installing symfony/dom-crawler (v3.0.2)
Downloading: 100%

symfony/var-dumper suggests installing ext-symfony_debug ()
symfony/translation suggests installing symfony/config ()
symfony/routing suggests installing symfony/config (For using the all-in-one rou
ter or any loader)
symfony/routing suggests installing symfony/expression-language (For using expre
ssion matching)
symfony/routing suggests installing doctrine/annotations (For using the annotati
on loader)
symfony/routing suggests installing symfony/dependency-injection (For loading ro
utes from a service)
symfony/event-dispatcher suggests installing symfony/dependency-injection ()
symfony/http-kernel suggests installing symfony/browser-kit ()
symfony/http-kernel suggests installing symfony/class-loader ()
symfony/http-kernel suggests installing symfony/config ()
symfony/http-kernel suggests installing symfony/dependency-injection ()
psy/psysh suggests installing ext-pcntl (Enabling the PCNTL extension makes PsyS
H a lot happier :))
psy/psysh suggests installing ext-posix (If you have PCNTL, you’ll want the POSI
X extension as well.)
psy/psysh suggests installing ext-readline (Enables support for arrow-key histor
y navigation, and showing and manipulating command history.)
psy/psysh suggests installing ext-pdo-sqlite (The doc command requires SQLite to
work.)
paragonie/random_compat suggests installing ext-libsodium (Provides a modern cry
pto API that can be used to generate random bytes.)
monolog/monolog suggests installing graylog2/gelf-php (Allow sending log message
s to a GrayLog2 server)
monolog/monolog suggests installing raven/raven (Allow sending log messages to a
Sentry server)
monolog/monolog suggests installing doctrine/couchdb (Allow sending log messages
to a CouchDB server)
monolog/monolog suggests installing ruflin/elastica (Allow sending log messages
to an Elastic Search server)
monolog/monolog suggests installing videlalvaro/php-amqplib (Allow sending log m
essages to an AMQP server using php-amqplib)
monolog/monolog suggests installing ext-amqp (Allow sending log messages to an A
MQP server (1.0+ required))
monolog/monolog suggests installing ext-mongo (Allow sending log messages to a M
ongoDB server)
monolog/monolog suggests installing aws/aws-sdk-php (Allow sending log messages
to AWS services like DynamoDB)
monolog/monolog suggests installing rollbar/rollbar (Allow sending log messages
to Rollbar)
monolog/monolog suggests installing php-console/php-console (Allow sending log m
essages to Google Chrome)
league/flysystem suggests installing ext-fileinfo (Required for MimeType)
league/flysystem suggests installing league/flysystem-eventable-filesystem (Allo
ws you to use EventableFilesystem)
league/flysystem suggests installing league/flysystem-rackspace (Allows you to u
se Rackspace Cloud Files)
league/flysystem suggests installing league/flysystem-copy (Allows you to use Co
py.com storage)
league/flysystem suggests installing league/flysystem-azure (Allows you to use W
indows Azure Blob storage)
league/flysystem suggests installing league/flysystem-webdav (Allows you to use
WebDAV storage)
league/flysystem suggests installing league/flysystem-aws-s3-v2 (Allows you to u
se S3 storage with AWS SDK v2)
league/flysystem suggests installing league/flysystem-aws-s3-v3 (Allows you to u
se S3 storage with AWS SDK v3)
league/flysystem suggests installing league/flysystem-dropbox (Allows you to use
Dropbox storage)
league/flysystem suggests installing league/flysystem-cached-adapter (Flysystem
adapter decorator for metadata caching)
league/flysystem suggests installing league/flysystem-sftp (Allows you to use SF
TP server storage via phpseclib)
league/flysystem suggests installing league/flysystem-ziparchive (Allows you to
use ZipArchive adapter)
laravel/framework suggests installing aws/aws-sdk-php (Required to use the SQS q
ueue driver and SES mail driver (~3.0).)
laravel/framework suggests installing doctrine/dbal (Required to rename columns
and drop SQLite columns (~2.4).)
laravel/framework suggests installing guzzlehttp/guzzle (Required to use the Mai
lgun and Mandrill mail drivers and the ping methods on schedules (~5.3|~6.0).)
laravel/framework suggests installing league/flysystem-aws-s3-v3 (Required to us
e the Flysystem S3 driver (~1.0).)
laravel/framework suggests installing league/flysystem-rackspace (Required to us
e the Flysystem Rackspace driver (~1.0).)
laravel/framework suggests installing pda/pheanstalk (Required to use the beanst
alk queue driver (~3.0).)
laravel/framework suggests installing predis/predis (Required to use the redis c
ache and queue drivers (~1.0).)
laravel/framework suggests installing pusher/pusher-php-server (Required to use
the Pusher broadcast driver (~2.0).)
fzaninotto/faker suggests installing ext-intl (*)
sebastian/global-state suggests installing ext-uopz (*)
phpdocumentor/reflection-docblock suggests installing dflydev/markdown (~1.0)
phpdocumentor/reflection-docblock suggests installing erusev/parsedown (~1.0)
phpunit/php-code-coverage suggests installing ext-xdebug (>=2.2.1)
phpunit/phpunit suggests installing phpunit/php-invoker (~1.1)
Writing lock file
Generating autoload files
> php artisan clear-compiled
> php artisan optimize
Generating optimized class loader
> php artisan key:generate
Application key [CZbM380YshFe0R8UK5zFMlYvL2Xa1WPG] set successfully.

6.跑完後,可以到下面網址看

http://localhost/laraveltest/public/