Codeigniter初めてのcontrollerデータ渡し

Route

ルーティングでは一旦default_controllerを使う - application/config/route.php

$route['default_controller'] = after; 

このafterがControllerのクラスになる

Controller

クラスを作っていきたいが afterクラスを作成するがここがポイント クラスのphpファイルには先頭を大文字で設定する - After.php

class After extends CI_Controller {
    public function index()
    {
        $data['message'] = 'Hello world!';
        $this->load->view('after', $data );
        }
}

View

viewsディレクトリにafter.phpを追加する

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>CodeIgniter</title>
</head>
<body>
<p><?php echo $message;?></p>
</body>
</html>

$data['message']で渡されたデータをview側で展開すると$messageでデータを取得することが可能となる

表示をみる

URLにアクセス http://example.com/index.php/before すると Hello world!が表示されていることが確認できます。

  • URLにindex.phpが含まれている

codeigniterの設定ではindex.phpを経由して表示させることからURLにも反映してしまう。 このURLを取り除きたい場合は.htaccessファイルをpublic_html配下にアップロードする。

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteCond $1 !^(index\.php|images|robots\.txt)
    RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>

上記ファイルを配置するだけで以下URLで表示を確認することができる。 http://example.com/before

まとめ

index.phpのURL排除に少しつまずいたものの簡単に確認することができました。 次回はDBを用いた記事を書きたいと思います。