」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 使用 Flight 建立簡單的部落格 - 第 1 部分

使用 Flight 建立簡單的部落格 - 第 1 部分

發佈於2024-08-01
瀏覽:249

Hey everyone! I figured it was time to showcase some of the new features that have been added to the Flight Framework for PHP. Earlier this year the original creator of Flight Mike Cao graciously offered to transfer ownership of mikecao/flight over to a new Flight PHP organization. Since it's been moved we've added features like middleware, route grouping, DIC, and other features. This post will be a little longer, but it's just because I've included a lot of code examples so you can have the right context into how your blog will get built.

First off, let's just get this out of the way. Flight is meant to be a simple framework with a few bells and whistles. It will not compete with Laravel or Symfony or Yii or Cake or [fill in the blank]. This framework is really built towards simple to medium size projects. It also caters to those who don't like "magic" in their code that's hard to understand or train to. It's geared more towards developers who are just starting to branch into frameworks instead of raw PHP with a lot of random include statements.

tl;dr

Lots of cool features, nice simple implementation, blah blah blah here's the code. Go to part 2 for the cool stuff!

Installation

Let's use Composer to get this party started.

composer create-project flightphp/skeleton blog/
cd blog/

Configure your New Project

First thing to do is to go to the app/config/config.php file where we can put any config like API keys, database credentials, and other important credentials for our app. For this blog, we'll uncomment the line with file_path for our SQLite database path:

return [
    'database' => [
        // 'host' => 'localhost',
        // 'dbname' => 'dbname',
        // 'user' => 'user',
        // 'password' => 'password'
        'file_path' => __DIR__ . $ds . '..' . $ds . 'database.sqlite'
    ],
];

Create the Blog Database

Flight now comes with a command line utility called runway. This allows you to create custom commands for a plugin for Flight, or even for your own project.

As part of the skeleton, it comes with a SampleDatabaseCommand that will give us a starting point with this blog project we are creating.

Run the below command and it should populate your database for you!

php runway init:sample-db

Next we'll open up the app/config/services.php file and uncomment the line for SQLite.

// see how the $config variable references the config line we uncommented earlier?
$dsn = 'sqlite:' . $config['database']['file_path'];

Just to make sure we've got everything setup correctly, run composer start and then go to http://localhost:8000/ in your browser. You should see the following screen:

Default Home Page

You'll also notice in the corner you have a handy debug toolbar with some custom Flight panels to help you understand what's going on in your application. If you hover over the various items in the toolbar, you'll see a variety of hovers that you can click on to keep sticky on the page (more on that later).

Flight Tracy Extensions

Building the HTML Templates

Flight does come with a very basic HTML templating solution already in the framework. This is just fine for very simple sites or just to return a simple piece of HTML. It is recommended to use another templating platform such as Latte, Twig, or Blade. In this tutorial, we're going to use Latte because it is awesome and has no dependencies (you'll notice in Flight we do not like unnecessary dependencies)!

Go ahead and install Latte

composer require latte/latte

Add this to your services.php

$Latte = new \Latte\Engine;
$Latte->setTempDirectory(__DIR__ . '/../cache/');

// This is fun feature of Flight. You can remap some built in functions with the framework
// to your liking. In this case, we're remapping the Flight::render() method.
$app->map('render', function(string $templatePath, array $data = [], ?string $block = null) use ($app, $Latte) {
    $templatePath = __DIR__ . '/../views/'. $templatePath;
    $Latte->render($templatePath, $data, $block);
});

Now that we have a templating engine in place, we can create a base HTML file. Let's create a layout.latte file:


    
        
        {$page_title ? $page_title.' - '}Blog Built with Flight!
        {block content}{/block}
    

Active Record Database Class

Flight has a plugin for interacting with a database called Flight Active Record. This plugin helps you not write as much raw SQL in your apps (although sometimes it is more efficient to write a raw SQL query instead of forcing an active record/ORM/mapper to run it for you). Basically the active record extension helps you interact with rows within tables in your database: one row in a database can be mapped to an object in PHP (with autocomplete for the columns) saving time and sanity. Let's get it installed in our project.

composer require flightphp/active-record

Now you can use runway to create your active record classes automatically for you and it will create your properties as comments automatically (for autocomplete)!

First let's create the posts class. The first time you run this, it needs to setup the connection for the database.

$ php runway make:record posts
Database configuration not found. Please provide the following details:
Driver (mysql/pgsql/sqlite): sqlite
Database file path [database.sqlite]: app/database.sqlite
Username (for no username, press enter) []: 
Password (for no password, press enter) []: 
Writing database configuration to .runway-config.json
Creating directory app/records
Active Record successfully created at app/records/PostRecord.php

Now we'll create the comments record class:

$ php runway make:record comments

It's Time for your First Page!

Flight uses the MVC pattern. In order to create a new page you need to define a route in your routes.php file, create a new method in a controller, and then create the HTML file that the browser will serve. You can use runway to help you get started with a new controller class:

php runway make:controller Home

And you should see something similar to the following:

$ php runway make:controller Home
Controller successfully created at app/controllers/HomeController.php

If you go to app/controllers/HomeController.php go ahead and add this new method to your HomeController:

/**
 * Index
 * 
 * @return void
 */
public function index(): void
{
    $this->app->render('home.latte', [ 'page_title' => 'Home' ]);
}

And create a new file in app/views/home.latte and put in this code:

{extends 'layout.latte'}

{block content}

My Home Page

View My Blog!

{/block}

Finally let's change up the routes to the routes.php file. Go ahead and remove any code in the routes file that begins with $router-> and add a new route for your home router:

$router->get('/', \app\controllers\HomeController::class . '->index');

Make sure you run composer start so that your development server is up. If you go to http://localhost:8000/ in your browser, you should see something like this!

Flight Demo Home Page

Now we're cookin'!

Adding Routes for the Blog

Let's go ahead and add all the methods in your controller, routes, and html files. Let's start with adding the routes in your routes.php file:

// Blog
$router->group('/blog', function(Router $router) {

    // Posts
    $router->get('', \app\controllers\PostController::class . '->index');
    $router->get('/create', \app\controllers\PostController::class . '->create');
    $router->post('', \app\controllers\PostController::class . '->store');
    $router->get('/@id', \app\controllers\PostController::class . '->show');
    $router->get('/@id/edit', \app\controllers\PostController::class . '->edit');
    $router->post('/@id/edit', \app\controllers\PostController::class . '->update');
    $router->get('/@id/delete', \app\controllers\PostController::class . '->destroy');
});

So you'll notice we use a group() method here to group all the routes together that start with /blog. We could actually rewrite the routes like the following with the group() method and the same thing would happen:

// Posts
$router->get('/blog', \app\controllers\PostController::class . '->index');
$router->get('/blog/create', \app\controllers\PostController::class . '->create');

With the controller, first let's create an empty controller with runway:

php runway make:controller Post

You can copy the code below for your PostController.php:

app = $app;
    }

    /**
     * Index
     *
     * @return void
     */
    public function index(): void
    {
        $PostRecord = new PostRecord($this->app->db());
        $posts = $PostRecord->order('id DESC')->findAll();
        $CommentRecord = new CommentRecord($this->app->db());
        foreach($posts as &$post) {
            $post->comments = $CommentRecord->eq('post_id', $post->id)->findAll();
        }
        $this->app->render('posts/index.latte', [ 'page_title' => 'Blog', 'posts' => $posts]);
    }

    /**
     * Create
     *
     * @return void
     */
    public function create(): void
    {
        $this->app->render('posts/create.latte', [ 'page_title' => 'Create Post']);
    }

    /**
     * Store
     *
     * @return void
     */
    public function store(): void
    {
        $postData = $this->app->request()->data;
        $PostRecord = new PostRecord($this->app->db());
        $PostRecord->title = $postData->title;
        $PostRecord->content = $postData->content;
        $PostRecord->username = $postData->username;
        $PostRecord->created_at = gmdate('Y-m-d H:i:s');
        $PostRecord->updated_at = null;
        $PostRecord->save();
        $this->app->redirect('/blog');
    }

    /**
     * Show
     *
     * @param int $id The ID of the post
     * @return void
     */
    public function show(int $id): void
    {
        $PostRecord = new PostRecord($this->app->db());
        $post = $PostRecord->find($id);
        $CommentRecord = new CommentRecord($this->app->db());
        $post->comments = $CommentRecord->eq('post_id', $post->id)->findAll();
        $this->app->render('posts/show.latte', [ 'page_title' => $post->title, 'post' => $post]);
    }

    /**
     * Edit
     *
     * @param int $id The ID of the post
     * @return void
     */
    public function edit(int $id): void
    {
        $PostRecord = new PostRecord($this->app->db());
        $post = $PostRecord->find($id);
        $this->app->render('posts/edit.latte', [ 'page_title' => 'Update Post', 'post' => $post]);
    }

    /**
     * Update
     *
     * @param int $id The ID of the post
     * @return void
     */
    public function update(int $id): void
    {
        $postData = $this->app->request()->data;
        $PostRecord = new PostRecord($this->app->db());
        $PostRecord->find($id);
        $PostRecord->title = $postData->title;
        $PostRecord->content = $postData->content;
        $PostRecord->username = $postData->username;
        $PostRecord->updated_at = gmdate('Y-m-d H:i:s');
        $PostRecord->save();
        $this->app->redirect('/blog');
    }

    /**
     * Destroy
     *
     * @param int $id The ID of the post
     * @return void
     */
    public function destroy(int $id): void
    {
        $PostRecord = new PostRecord($this->app->db());
        $post = $PostRecord->find($id);
        $post->delete();
        $this->app->redirect('/blog');
    }
}

Let's kill some time and talk about a few things that are going on in the controller.

First off we are now using our new active record classes:

$PostRecord = new PostRecord($this->app->db());
$posts = $PostRecord->order('id DESC')->findAll();

We are injecting the database we setup in the services.php file above with $this->app->db();. Technically we could also just use Flight::db() as this points to the global $app variable.

Active Record classes are really helpful to simplify interactions with a database. We could rewrite the above in the following code:

$posts = $this->app->db()->fetchAll("SELECT * FROM posts ORDER BY id DESC");

This might not be the best example of how helpful an active record could be. But in part 2 I'll show you some hidden gems inside these classes that make it so much better than writing raw SQL.

Now let's talk HTML files. Here are the files we'll need for the post routes:

app/views/posts/index.latte

{extends '../layout.latte'}

{block content}

My Amazing Blog

Welcome to my blog!

Create a new post

{foreach $posts as $post} {first}

Recent Posts

{/first}

{$post->title}

By: {$post->username} on {$post->created_at|date:'d.m.Y G:i a'}

Comments: {count($post->comments)}

{$post->content|truncate:100}


Update - Delete {/foreach} {/block}

app/views/posts/show.latte

{extends '../layout.latte'}

{block content}
< Back to blog

{$post->title}

Created by: {$post->username} on {$post->created_at|date:'d.m.Y G:i a'}.

{$post->content|breakLines}

Last update: {$post->update_at|date:'d.m.Y G:i a'}.

Comments

{foreach $post->comments as $comment}

{$comment->username} on {$comment->created_at|date:'d.m.Y G:i a'}.

{$comment->content|breakLines}

Delete
{else}

No comments yet.

{/foreach}

Add comment

{/block}

app/views/posts/create.latte

{extends '../layout.latte'}

{block content}

Create a Post

{/block}

app/views/posts/edit.latte

{extends '../layout.latte'}

{block content}

Update a Post

{/block}

Create a new post

Now that we've got all the pieces in place, you should be able to load up your blog page, create a new post, see a post, and delete a post. You may have noticed we've included a comment form but the form doesn't actually work. We can fix that real quick! Let's create a controller with runway:

php runway make:controller Comment

Now you can make the CommentController.php look like the following:

app = $app;
    }

    /**
     * Store
     * 
     * @param int $id The post ID
     * 
     * @return void
     */
    public function store(int $id): void
    {
        $postData = $this->app->request()->data;
        $CommentRecord = new CommentRecord($this->app->db());
        $CommentRecord->post_id = $id;
        $CommentRecord->username = $postData->username;
        $CommentRecord->content = $postData->content;
        $CommentRecord->created_at = gmdate('Y-m-d H:i:s');
        $CommentRecord->updated_at = null;
        $CommentRecord->save();
        $this->app->redirect('/blog/' . $id);
    }

    /**
     * Destroy
     * 
     * @param int $id The post ID
     * @param int $comment_id The comment ID
     * 
     * @return void
     */
    public function destroy(int $id, int $comment_id): void
    {
        $CommentRecord = new CommentRecord($this->app->db());
        $CommentRecord->find($comment_id);
        $CommentRecord->delete();
        $this->app->redirect('/blog/' . $id);
    }

}

Now let's add a couple other routes in the group chunk of code in routes.php

// Blog
$router->group('/blog', function(Router $router) {

    // Posts

    // post routes...

    // Comments
    $router->post('/@id/comment', \app\controllers\CommentController::class . '->store');
    $router->get('/@id/comment/@comment_id/delete', \app\controllers\CommentController::class . '->destroy');
});

Conclusion (sort of)

With these two additions to the code, you have a fully functioning blog built with Flight! This got the job done and you now have a blog, but the code is somewhat clunky and could be improved to have some pretty nifty features like middleware, permissions, and writing less code! Hop over to part 2

Go ahead and leave any questions in comments below or join us in the chatroom!

If you want to see the final product with all the improvements here's the code!

版本聲明 本文轉載於:https://dev.to/n0nag0n/building-a-simple-blog-with-flight-part-1-4ap8?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>
  • extjs API 查詢參數範例
    extjs API 查詢參數範例
    API 查詢 參數是附加到 API 請求 URL 的鍵值對,用於傳送附加資訊至伺服器。它們允許用戶端(例如 Web 瀏覽器或應用程式)在向伺服器發出請求時指定某些條件或傳遞資料。 查詢參數加入到 URL 末端問號 (?) 後。每個參數都是鍵值對,鍵和值之間以等號 (=) 分隔。如果有多個查詢參數,...
    程式設計 發佈於2024-11-05
  • 如何解決Go中從不同套件匯入Proto檔案時出現「Missing Method Protoreflect」錯誤?
    如何解決Go中從不同套件匯入Proto檔案時出現「Missing Method Protoreflect」錯誤?
    如何從不同的套件導入Proto 檔案而不遇到「Missing Method Protoreflect」錯誤在Go 中,protobuf 常用於資料序列化。將 protobuf 組織到不同的套件中時,可能會遇到與缺少 ProtoReflect 方法相關的錯誤。當嘗試將資料解組到單獨套件中定義的自訂 p...
    程式設計 發佈於2024-11-05
  • 為什麼MySQL在查詢「Field = 0」非數位資料時傳回所有行?
    為什麼MySQL在查詢「Field = 0」非數位資料時傳回所有行?
    不明確的查詢:理解為什麼MySQL 回傳「Field=0」的所有行在MySQL 查詢領域,一個看似無害的比較,例如“SELECT * FROM table WHERE email=0”,可能會產生意外的結果。它沒有按預期過濾特定行,而是返回表中的所有記錄,從而引發了對資料安全性和查詢完整性的擔憂。 ...
    程式設計 發佈於2024-11-05
  • 伺服器發送事件 (SSE) 的工作原理
    伺服器發送事件 (SSE) 的工作原理
    SSE(服务器发送事件)在 Web 开发领域并未广泛使用,本文将深入探讨 SSE 是什么、它是如何工作的以及它如何受益您的申请。 什么是上交所? SSE 是一种通过 HTTP 连接从服务器向客户端发送实时更新的简单而有效的方法。它是 HTML5 规范的一部分,并受到所有现代 Web ...
    程式設計 發佈於2024-11-05
  • 如何從字串 TraceID 建立 OpenTelemetry Span?
    如何從字串 TraceID 建立 OpenTelemetry Span?
    從字串 TraceID 建構 OpenTelemetry Span要建立 Span 之間的父子關係,必須在上下文傳播不可行的情況下使用標頭。在這種情況下,追蹤 ID 和跨度 ID 包含在訊息代理程式的標頭中,這允許訂閱者使用父追蹤 ID 建立新的跨度。 解決方案以下步驟可以使用追蹤ID 在訂閱者端建...
    程式設計 發佈於2024-11-05
  • 如何在gRPC中實現伺服器到客戶端的廣播?
    如何在gRPC中實現伺服器到客戶端的廣播?
    gRPC 中的廣播:伺服器到客戶端通訊建立gRPC 連線時,通常需要將事件或更新從伺服器廣播到客戶端連接的客戶端。為了實現這一點,可以採用各種方法。 Stream Observables常見的方法是利用伺服器端流。每個連線的客戶端都與伺服器建立自己的流。然而,直接訂閱其他伺服器客戶端流是不可行的。 ...
    程式設計 發佈於2024-11-05
  • 為什麼填入在 Safari 和 IE 選擇清單中不起作用?
    為什麼填入在 Safari 和 IE 選擇清單中不起作用?
    在Safari 和IE 的選擇清單中不顯示填充儘管W3 規範中沒有限制,但WebKit 瀏覽器不支援選擇框中的填充,包括Safari和Chrome。因此,這些瀏覽器中不應用填充。 要解決此問題,請考慮使用 text-indent 而不是 padding-left。透過相應增加選擇框的寬度來保持相同的...
    程式設計 發佈於2024-11-05
  • 在 Spring Boot 中建立自訂註解的終極指南
    在 Spring Boot 中建立自訂註解的終極指南
    Such annotations fill the entire project in Spring Boot. But do you know what problems these annotations solve? Why were custom annotations introduce...
    程式設計 發佈於2024-11-05
  • 為什麼 Elixir 在非同步處理方面比 Node.js 更好?
    為什麼 Elixir 在非同步處理方面比 Node.js 更好?
    简单回答:Node.js 是单线程的,并拆分该单线程来模拟并发,而 Elixir 利用了 Erlang 虚拟机 BEAM 原生的并发和并行性,同时执行进程。 下面,我们将更深入地了解这种差异,探索两个关键概念:Node.js 事件循环和 Elixir 的 BEAM VM 和 OTP。这些元素对于理解...
    程式設計 發佈於2024-11-05
  • AngularJS $watch 如何取代動態導航高度調整中的計時器?
    AngularJS $watch 如何取代動態導航高度調整中的計時器?
    避免 AngularJS 的高度監視計時器當導航高度是動態時,AngularJS 程式設計師經常面臨響應式導航的挑戰。這就導致需要調整內容的 margin-top 值以回應導航高度的變化。 以前,使用計時器來偵測導航高度的變化,但這種方法有缺點:使用計時器和調整內容的 margin-top 出現延遲...
    程式設計 發佈於2024-11-05
  • 從零到 Web 開發人員:掌握 PHP 基礎知識
    從零到 Web 開發人員:掌握 PHP 基礎知識
    掌握PHP基礎至關重要:安裝PHP建立PHP檔案運行程式碼理解變數和資料類型使用表達式和運算子建立實際專案以提高技能 PHP開發入門:掌握PHP基礎PHP是一種用途廣泛、功能強大的腳本語言,用於創建動態且互動式Web應用程式。對於初學者來說,掌握PHP的基本知識至關重要。 一、安裝PHP在本地開發機...
    程式設計 發佈於2024-11-05
  • 緩衝區:Node.js
    緩衝區:Node.js
    Node.js 中緩衝區的簡單指南 Node.js 中的 Buffer 用於處理原始二進位數據,這在處理流、文件或網路數據時非常有用。 如何建立緩衝區 來自字串: const buf = Buffer.from('Hello'); 分配特定大小的Buffer...
    程式設計 發佈於2024-11-05
  • 掌握 Node.js 中的版本管理
    掌握 Node.js 中的版本管理
    作為開發者,我們經常遇到需要不同 Node.js 版本的專案。對於可能不經常參與 Node.js 專案的新手和經驗豐富的開發人員來說,這種情況都是一個陷阱:確保每個專案使用正確的 Node.js 版本。 在安裝依賴項並執行專案之前,驗證您的 Node.js 版本是否符合或至少相容專案的要求至關重要...
    程式設計 發佈於2024-11-05
  • 如何在 Go 二進位檔案中嵌入 Git 修訂資訊以進行故障排除?
    如何在 Go 二進位檔案中嵌入 Git 修訂資訊以進行故障排除?
    確定Go 二進位檔案中的Git 修訂版部署程式碼時,將二進位檔案與建置它們的git 修訂版關聯起來會很有幫助排除故障的目的。然而,直接使用修訂號更新原始程式碼是不可行的,因為它會改變原始程式碼。 解決方案:利用建造標誌解決此挑戰的方法包括利用建造標誌。透過使用建置標誌在主套件中設定當前 git 修訂...
    程式設計 發佈於2024-11-05
  • 常見 HTML 標籤:視角
    常見 HTML 標籤:視角
    HTML(超文本標記語言)構成了 Web 開發的基礎,是互聯網上每個網頁的結構。透過了解最常見的 HTML 標籤及其高級用途,到 2024 年,開發人員可以創建更有效率、更易於存取且更具視覺吸引力的網頁。在這篇文章中,我們將探討這些 HTML 標籤及其最高級的用例,以協助您提升 Web 開發技能。 ...
    程式設計 發佈於2024-11-05

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3