PHPフレームワークであるPhalcon入門-パート2

提供:Dev Guides
移動先:案内検索


ステータス:非推奨

この記事では、サポートされなくなったバージョンのUbuntuについて説明します。 現在Ubuntu12.04を実行しているサーバーを運用している場合は、サポートされているバージョンのUbuntuにアップグレードまたは移行することを強くお勧めします。

理由: Ubuntu 12.04は2017年4月28日に保守終了(EOL)に達しました and no longer receives security patches or updates. This guide is no longer maintained.

代わりに参照してください:
このガイドは参照として役立つ場合がありますが、他のUbuntuリリースでは機能しない場合があります。 可能な場合は、使用しているUbuntuのバージョン用に作成されたガイドを使用することを強くお勧めします。 ページ上部の検索機能を使用して、より新しいバージョンを見つけることができます。


PhalconPHPについて


Phalcon は、Model-View-Controllerアーキテクチャを促進するPHPフレームワークであり、ORM、テンプレートエンジン、ルーティング、キャッシングなど、ソフトウェアに期待される多くのフレームワークのような機能を備えています。 。

このチュートリアルでは、Ubuntu 12.04 VPSにPhalconをインストールし、最初の文字列をPhalconコントローラーを使用した画面。 このチュートリアルでは、他の2つのコアMVCコンポーネントであるビューとモデルの使用について説明します。

この記事を続けるために、前のチュートリアルで概説した手順を実行し、Phalconアプリケーションで HelloWorldを印刷していることを前提としています。ブラウザからip-address/project-nameにアクセスします。 では、掘り下げてみましょう。

ビュー


前のチュートリアルでは、これを行う1つのメソッド(IndexAction)を使用してデフォルトのインデックスコントローラーを作成しました。

echo "<h1>Hello World!</h1>";


As you know, this is not the best way to print things onto the screen; and like other PHP frameworks out there, Phalcon comes with a templating system that we should use instead. In other words, we can use a View and pass the こんにちは世界 string to it through a variable.

The way this works with Phalcon is that in the アプリ/ビュー folder we need to create another folder named as our controller and inside this folder a file named after the controller’s action. This way, Phalcon autoloads this view when the controller action is called. So let’s do this for our first controller/action 索引. Create the folder first:

mkdir /var/www/project_name/app/views/index


Inside this folder, create a the file with a phtml extension (named after the controller action):

nano /var/www/project_name/app/views/index/index.phtml


Inside this file, cut the contents of the IndexAction from the controller and paste it in there, between tags:

<?php echo "<h1>Hello World!</h1>"; ?>


Now the controller action is empty, yet the string gets printed from the view that corresponds to that controller/action. So in this short example we have not passed anything to the view yet from the controller, we just demonstrated how the view is loaded automatically. Let’s now declare that variable in our controller, and then pass it to the view to be displayed.

Go back to the IndexController and inside the indexAction method, paste in the following (making sure this is all there is inside this function):

$string = "Hello World!";
$this->view->setVar("string", $string);


In the first line, we set our text value to the $ string variable and in the second one we use the setVar method of the 見る() method of our parent controller class to send this variable to another one that can be accessed inside the view: also called $ string.

Now edit the view and replace this:

<?php echo "<h1>Hello World!</h1>"; ?>


With this:

<h1><?php echo $string; ?></h1>


Now you should get the same thing in the browser. Like this, we separated logic (our string value that for all intents and purposes could have been dynamically generated or retrieved) from presentation (the html header tag we wrapped around the string in the View). This is one of the tenets of the MVC architecture and good modern programming practice.

モデルとデータベース


コントローラとビューを確認したので、データベースを接続して、モデルを使用してデータベースと対話する方法を見てみましょう。 ここから先に進むには、使用できるデータベースがすでにあり、そのアクセスクレデンシャルを知っており、基本的なMySQLコマンドに精通していることを前提としています。 そうでない場合は、このチュートリアルを確認してください。

データベースに接続するには、前の記事で作成したブートストラップファイル、public/フォルダーにあるindex.phpファイルを編集する必要があります。

nano /var/www/project_name/public/index.php


Under this block:

  //Setup a base URI so that all generated URIs include the "tutorial" folder
    $di->set('url', function(){
        $url = new \Phalcon\Mvc\Url();
        $url->setBaseUri('/project/');
        return $url;
    });


Add the following block:

  //Setup the database service
    $di->set('db', function(){
        return new \Phalcon\Db\Adapter\Pdo\Mysql(array(
            "host" => "localhost",
            "username" => "root",
            "password" => "password",
            "dbname" => "db-name"
        ));
    });


And of course replace where appropriate with your database information. Save the file and exit. Next, create a table that will host your first model. Let’s call it 記事 and give it an ID column, a title column, and a body column. The following MySQL command will create it for you.

CREATE TABLE `articles` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `title` varchar(255) NOT NULL,
  `body` text NOT NULL,
  PRIMARY KEY (`id`)
);


Let’s now insert a row through our command line to have something to play with. You can use this MySQL command to do it if you want:

INSERT INTO `articles` (title, body)  VALUES ('This is the first article', 'some article body');


Now that we have some content, let's define our Article model. Create a php file in the app/models folder of your application:

nano /var/www/project_name/app/models/Articles.php


And paste this inside (omit the closing php tag):

<?php

class Articles extends \Phalcon\Mvc\Model {

}


We are now extending the Phalcon model class, which provides a lot of useful functionality for us to interact with our model data. Another cool thing is that since we named the class as we did the database table, the two are already linked. This model will refer to that database table.

Now what we need to do is declare our model properties (that map to the table columns). So inside the class, add the following protected properties:

public $id;

public $title;

public $body;


Next, we need some setters/getters to retrieve from or to assign values to these protected properties. And here we can have a lot to control over how the data can be accessed. But since this tutorial will not look into adding information to the database, we will only add one getter function to retrieve existing information from the property. So below, but still inside the model class, add the following methods:

public function getId()    {
    return $this->id;
}

public function getTitle()    {
    return $this->title;
}

public function getBody()    {
    return $this->body;
}


Normally however, you’ll also need setter functions. Let's save this file and turn back to our IndexController. Inside the IndexAction, replace all the contents with the following:

$article = Articles::findFirst(1);
$this->view->setVar("string", $article->getTitle());


On the first line we use the findFirst method of the Phalcon model class from which we extended our 記事 model to retrieve the article with the ID of 1. Then in the second one, we pass to the View the value of the title column that we are retrieving with our getter function we declared in the model earlier. Save the file and reload the browser. You should see printed out the title of the first article.

Since we cannot go into all what you can do with the Phalcon model class, I encourage you to read more about it ここ. You will find a bunch of ready functionality and database abstraction to get you going fast.

結論


このチュートリアルでは、プロジェクトフォルダー構造に配置されたビューがPhalconによって自動的に読み込まれる方法と、コントローラーアクションからそれぞれのビューに情報を渡す方法について説明しました。 さらに、データベーステーブルを操作して情報を取得する方法を確認するために、小さなPhalconモデルを設定しました。

投稿者: Danny