1. 程式人生 > >Laravel隱式控制器、快取、常用操作

Laravel隱式控制器、快取、常用操作

隱式控制器

路由宣告:

Route::controller('users', 'UsController');
  • 1

控制器寫法

class UsController extends Controller
{
    //get請求預設方法
    //位址列請求:http://xx.com/users
    public function getIndex(){
        echo 123;
    }

    //位址列請求:http://xx.com/users/add
    public function getAdd(){
        echo 'ass';
    }
    //POST提交請求:http://xx.com/users/add
public function postAdd(){ echo 'postAdd'; } }

快取

路由快取

在你的專案部署完成後執行

php artisan route:cache
  • 1

生成路由快取,快取一旦生成,app/Http/routes.php 檔案將失去作用;

想要清除快取路由執行:

php artisan route:clear
  • 1

使用路由快取可以大幅降低註冊全部路由所需的時間。在某些情況下,你的路由註冊甚至可以快上一百倍!

檔案快取

laravel有很多快取方式,預設使用檔案(file),但是不管用哪種快取都需要先引入快取基類 use Cache;

新增快取:

//鍵,值,有時間

//有則修改,無則新增,無返回值
Cache::put('key', 'value', $minutes);

//有則返回false,新增失敗;
//無則返回true,新增成功;
Cache::add('key', 'value', $minutes);

//新增永久有效資料,除非手動刪除,否則不失效
Cache::forever('key', 'value');

獲取快取:

//返回快取中的值
$value = Cache::get('key');

//如果沒有值,或者已經失效,返回 'default'
$value = Cache::get('key', 'default'
); //如果沒有'key',函式會被呼叫, $value = Cache::get('key', function() { //重新寫入快取 Cache::put('ke', 'valueeee','1'); //返回123 return 123; }); //獲取並刪除快取 Cache::pull('key');

判斷是否有快取:Cache::has('key')

刪除快取:

//刪除快取
Cache::forget('key');
//清空所有快取
Cache::flush();

檔案系統

use Storage;

檔案預設存放地址: 
storage/app

檔案常用操作:

//儲存資訊到檔案中:
Storage::put('file.jpg', '123');

//將資料在檔案開頭處插入
Storage::prepend('file.log', 'Prepended Text');
//將資料在檔案結尾處插入
Storage::append('file.log', 'Appended Text');

//獲取檔案中的資訊:
Storage::get('file.jpg');

//複製檔案
Storage::copy('old/file1.jpg', 'new/file1.jpg');

//剪下檔案
Storage::move('old/file1.jpg', 'new/file1.jpg');

//刪除檔案
Storage::delete('file.jpg');
Storage::delete(['file1.jpg', 'file2.jpg']);

//獲取檔案的大小並以 bytes 單位返回
$size = Storage::size('file1.jpg');

//最後修改時間並返回 UNIX 時間戳
$time = Storage::lastModified('file1.jpg');

目錄常用操作:

//建立指定的目錄
Storage::makeDirectory('/a/b/c');

//移除磁碟上的單個目錄以及所包含的全部檔案
Storage::deleteDirectory($directory);

//返回指定目錄下的目錄陣列
$directories = Storage::directories($directory);
// 遞迴...
$directories = Storage::allDirectories($directory);

//返回指定目錄下的檔名陣列
$files = Storage::files($directory);

//返回包含指定目錄下所有子目錄的檔案
Storage::allFiles($directory);