iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 25
0
Modern Web

每日文章推薦系列 第 25

Day 25 從codeigniter換到laravel

  • 分享至 

  • xImage
  •  

首先

兩者都是好工具

並沒有說哪個比較好哪個比較不好

從model到Eloquent

用過codeigniter的 就會知道他的model根本是空的XDD

基本上就是要啥功能自己加

他就只是一個空的class

但是內部有提供query builder的功能

class Blog_model extends CI_Model {

        public $title;
        public $content;
        public $date;

        public function __construct()
        {
                parent::__construct();
                // Your own constructor code
        }

        public function get_last_ten_entries()
        {
                $query = $this->db->get('entries', 10);
                return $query->result();
        }

        public function insert_entry()
        {
                $this->title    = $_POST['title']; // please read the below note
                $this->content  = $_POST['content'];
                $this->date     = time();

                $this->db->insert('entries', $this);
        }

        public function update_entry()
        {
                $this->title    = $_POST['title'];
                $this->content  = $_POST['content'];
                $this->date     = time();

                $this->db->update('entries', $this, array('id' => $_POST['id']));
        }

}

https://codeigniter.org.tw/userguide3/general/models.html#id3

改成用laravel以後 一定會先嘗試用Eloquent

假設從頭建立的話 可以用

php artisan make:model Blog
#result
Model created successfully.
# 如果要連migration一起產生的話 可以下
php artisan make:model Blog -m
Model created successfully.
Created Migration: 2017_12_28_135251_create_blogs_table
## 如果你真的懶到不行 可以下
php artisan make:model Blog -mrc

laravel 就會幫你新增出來一個Blog.php的檔案

因為Eloquent是個orm 所以他可以自動去連相應的table

所以如果我們要做跟上面那個model一樣的事情

要這樣改

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Blog extends Model
{
    protected $table='entries';
    public function get_last_ten_entries()
    {
        return $this->latest()->take(10)->get();

    }

}

會發現我只放了一個function

原因是Eloquent本身就有Blog::create() 跟 Blog::update()可以呼叫

所以就可以先放著不管了

另外是可以多嘗試使用Eloquent的Relationships

可以很直覺的把資料關聯性弄出來

不用自幹

另laravel還提供了collections

可以在處理資料時省下不少麻煩

從view 到blade

CodeIgniter 的樣板引擎就是原生的php 並沒有其他的語法需要學習

只是提供了view這個工具讓你方便套用版型跟把資料匯入

而laravel預設使用blade這個樣板引擎

提供了很多有的沒的功能

可以很方便的共用版型

讓你寫的時候只要注意該放資料的部分就好

習慣就好

基本上每個工具都是有他自己的特性

不見得分好壞

雖然我上面好像把CodeIgniter講的很陽春

但是這也是他的優點 沒有非必要的部分

但如果你需要其他功能 也可以利用composer自行擴充

你開心的話也可以在CodeIgniter裡面用laravel的blade跟Eloquent

或者是其他你喜歡用的工具

總結

Laravel提供了一套規範讓你參考

也提供了很多方便的工具

雖然一開始用起來可能會感覺綁手綁腳的不自由

但是理解它的存在原因以後就會覺得很方便

CodeIgniter 就是個隨拆即用的工具包

功能不見得多 但是夠用

只是架構陽春要自行擴張

今天分享的文章

今天看的文章

https://github.com/fripig/article_log/issues/433


上一篇
Day 24 自幹是工程師的浪漫
下一篇
day 26
系列文
每日文章推薦30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言