情弱エンジニアのなかのblog

一人前のエンジニアになる為のブログです

CakePHPでComponentの実装

使いまわせて便利なComponent!

現在CakePHPでアプリを制作していまして、Componentを実装したので手順等を記載致します。

商品の紹介記事を投稿するアプリで記事データ(articles)には商品データ(products)がひもづいていて、その商品データには商品を売っている企業のデータ(companies)が紐づいています。 企業ごとの記事の数を企業の一覧表示画面で確認するという機能を制作致しました。

1.Componentの作成

まずはapp/Controller/ComponentにComponentファイルを作成します。

class CustomComponent extends Component {


public function get_article_count($table_name,$field_name,$this_list_count) {

    //記事データを取得できるようにする
    $article_data = ClassRegistry::init('Article');

    //検索用に文字列を繋げる
    $table_field = $table_name . "." . $field_name;

    //記事データと記事データに付随する記事数を取得したいフィールド情報を取得する
    $article_list = $article_data->find('all', array('fields' => array($table_field)));

    //記事ごとの目的のフィードの値を取得する
    for($i = 0; $i < count($article_list); $i++) {
        $field_id_list[$i] = $article_list[$i][$table_name][$field_name];
    }

    //記事数を代入する
    $article_count = count($field_id_list);

    //記事数を取得したいフィールドの数分配列を用意する
    for($i = 1; $i <= $this_list_count; $i++) {
        $field_each_article_count[$i] = 0;
    }

    //記事数を取得したいフィールドごとの記事の数を配列に代入する
    for($i = 0; $i < $article_count; $i++) {
        for($j = 1; $j <= $this_list_count; $j++) {

            if($field_id_list[$i] == $j) {
                //フィールドごとの検索をして記事データがあったら
                //記事の数を加算していく
                $field_each_article_count[$j]++;
                continue;
            }
        }
    }

    return $field_each_article_count;
}

}

これを作っていれば複数のControllerでフィールドごとの記事の数を取得できます。

2.Controllerでデータを渡す

Controllerからデータを渡して、記事の数を取得します。 今回はサイトごとの記事の数を取得します。

public function index() {
    
    $table_name = "Product";
    $field_name = "company_id";
    //サイトの数を取得する
    $site_count = count($this->Company->find('list'));
    //各サイトごとの記事数を取得する
    $company_each_article_count = $this->Custom->get_article_count($table_name,$field_name,$site_count);

    $this->set('company_each_article_count',$company_each_article_count);
    $this->set('companies', $this->Paginator->paginate());
}

この形式の処理をControllerに書くことで様々なフィールドごとの記事数を取得できます。

3.indexで表示する

最後にindexでサイト名の横に記事数を表示します。

<?php foreach ($companies as $id => $company): ?>
//サイト名を一覧する処理
<td>
    <?php
    $id++;
    echo $company_each_article_count[$id];
    ?>
</td>

これでComponentにフィールドごとに記事数を取得する処理を作ることが出来ました。

もっと効率的に実装する方法もあるかと思うのですがとりあえずはここまでで 出来たらまたアップします。

それでは