• Ubuntuに関連したハード、ソフトの備忘録サイトです

「CodeIgniter徹底入門」の2.x系への対応(3)ーCRUDと認証機能【暫定投稿】

CodeIgniterの2.はx系列では非推奨のCRUDが外されました。また、認証機能が標準でないかも知れません。ということで、サードパーティ製のCRUDシステムと認証システムがありましたので、簡易管理画面を作成してみました。

CRUDシステムは、http://www.grocerycrud.com/のもので、最新版は1.5.0でしたが、CodeIgniter2.0でも使えるようです。また、認証システムは、https://github.com/DaBourz/SimpleLoginSecureにありました。これらのシステムを使って、簡易ショッピングサイトに認証機能付き簡易バックエンドをこしらえてみました。

1.インストール
いずれも、zip形式になっていますので、unzipで解凍してできたapplicationディレクトリをCodeIgniterのapplicationディレクトリに上書きコピーします。controllerディレとクリには、CRUDシステム、認証システムのサンプル・コードとして、examples.php, login_sample.phpが入りますので、これを変更すれば良いことになります。

2.login_sample.phpの変更内容。次のようにしました。

output->set_header('Content-Type: text/html; charset=UTF-8');

		// simpleloginなどのライブラリをロードする。
		$this->load->library(array('simpleLoginSecure', 'session', 'form_validation'));
		$this->load->database();
		$this->load->helper(array('form', 'url'));
		$this->load->model('Shop_model');
	}

	function index()
	{
		if ($this->session->userdata('logged_in'))
		{
			// ユーザログイン中
			//echo 'あなたはログイン中です';
			//echo anchor('login_sample/logout', 'ログアウトする');
			redirect('shop_table');
		}
		else
		{
			// ユーザ非ログイン
			//echo 'あなたはログインしていません';
			redirect('login_sample/login');
		}
	}

	function login()
	{
		// バリデーションのルール設定を行ないます。$this->validation->set_rules()メソッドでルールを適用します。
		$this->form_validation->set_rules('username', 'メールアドレス', "trim|required|email");
		$this->form_validation->set_rules('password', 'パスワード', "trim|required");

		// 検証エラーまたは初回アクセス時
		if ($this->form_validation->run() == FALSE)
		{
			$data['list'] = $this->Shop_model->get_category_list();
			$data['menu'] = $this->load->view('shop_menu', $data, TRUE);
			//$this->load->view('user_login');
			$data['main']   = $this->load->view('user_login', $data, TRUE);
			$data['item_count'] = $this->Shop_model->get_cart_item_count();
			$data['header'] = $this->load->view('shop_header', $data, TRUE);
			$this->load->view('shop_tmpl_shop', $data);
		}
		else
		{
			// ログインメソッド実行
			$result = $this->simpleloginsecure->login($this->input->post('username'),
			$this->input->post('password'));

			// 結果の検証
			if ($result == TRUE)
			{
				// リダイレクトする
				//redirect('login_sample/', 'refresh');
				redirect('shop_tables/index');
			}
			else
			{
				echo anchor('login_sample/login', 'もう一度');
			}
		}
	}

	function create()
	{
		// バリデーションのルール設定を行ないます。$this->validation->set_rules()メソッドでルールを適用します。
		$this->form_validation->set_rules('username', 'メールアドレス', "trim|required|email");
		$this->form_validation->set_rules('password', 'パスワード', "trim|required");

		// 検証エラーまたは初回アクセス時
		if ($this->form_validation->run() == FALSE)
		{
			$this->load->view('user_create');
		}
		else
		{
			// ログインメソッド実行
			$result = $this->simpleloginsecure->create($this->input->post('username'),
			$this->input->post('password'));

			// 結果の検証
			if ($result == TRUE)
			{
				// リダイレクトする
				//redirect('login_sample/', 'refresh');
				echo "アカウントの作成に成功しました。";
				redirect('shop/index');
			}
			else
			{
				echo 'アカウントの作成に失敗しました。';
				echo anchor('login_sample/create', 'もう一度');
			}
		}
	}

	function logout()
	{
		// ログアウトメソッド実行
		$this->simpleloginsecure->logout();
		echo 'ログアウトしました';
		echo anchor('shop', 'ショッピングサイトへ');
	}
}
?>

このサンプルの前に、データベースにusersテーブルを作成することが必要になります。sqlのテキストファイルが入っていますので、mysql -uroot -p database < create_users_table.sqlを実行しておきます。

2.CRUDシステムのcontroller/examples.php -> controller/shop_tables.phpの変更点

load->database();
		$this->load->helper('url');
		$this->load->library('grocery_CRUD');


		// simpleloginなどのライブラリをロードする。
		$this->output->set_header('Content-Type: text/html; charset=UTF-8');
		$this->load->library(array('simpleLoginSecure', 'session', 'form_validation'));
		$this->load->database();
		$this->load->helper(array('form', 'url'));


	}

	public function _example_output($output = null)
	{
		$this->load->view('shop_tables_view',$output);
	}

	public function index()
	{
		//Login
		if ($this->session->userdata('logged_in'))
		{
			// ユーザログイン中
			//echo 'あなたはログイン中です';
			//echo anchor('login_sample/logout', 'ログアウトする');
			//redirect('shop_table/index');
			//$this->_example_output((object)array('output' => '' , 'js_files' => array() , 'css_files' => array()));
			$this->product();
		}
		else
		{
			// ユーザ非ログイン
			//echo 'あなたはログインしていません。管理画面に入るにはログインする必要があります。';
			//echo anchor('login_sample/login', 'ログインフォームへ');
			redirect('login_sample/login');
		}
	}

	public function category()
	{
		try{
			$crud = new grocery_CRUD();

			$crud->set_theme('datatables');
			$crud->set_table('category');
			$crud->set_subject('製品カテゴリー');
			$crud->required_fields('name');
			$crud->columns('name');

			$output = $crud->render();

			$this->_example_output($output);

		}
		catch(Exception $e)
		{
			show_error($e->getMessage().' --- '.$e->getTraceAsString());
		}
	}

	public function product()
	{
		try{
			$crud = new grocery_CRUD();

			$crud->set_theme('datatables');
			$crud->set_table('product');
			$crud->set_subject('ショップ製品');
			$crud->required_fields('name');
			$crud->columns('category_id', 'name','detail','price','img');

			$output = $crud->render();

			$this->_example_output($output);

		}
		catch(Exception $e)
		{
			show_error($e->getMessage().' --- '.$e->getTraceAsString());
		}
	}

}

これは、曲がりなりにもバックエンドになりますので、認証が必要になります。FuelPHPなどではコンストラクタに記載するようですが、function index()で場合分けをしています。

3.CRUDシステムのviews/examples.php -> viewsr/shop_tables_view.phpの変更点

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
<?php 
foreach($css_files as $file): ?>
	<link type="text/css" rel="stylesheet" href="<?php echo $file; ?>" />
<?php endforeach; ?>
<?php foreach($js_files as $file): ?>
	<script src="<?php echo $file; ?>"></script>
<?php endforeach; ?>
<style type='text/css'>
body
{
	font-family: Arial;
	font-size: 14px;
}
a {
    color: blue;
    text-decoration: none;
    font-size: 14px;
}
a:hover
{
	text-decoration: underline;
}
</style>
</head>
<body>
	<div>
		<a href='<?php echo site_url('shop_tables/category')?>'>カテゴリー</a> |
		<a href='<?php echo site_url('shop_tables/product')?>'>製品</a> |
	</div>
	<div style='height:20px;'></div>  
    <div>
		<?php echo $output; ?>
    </div>
	<br />
	<hr />
<?php echo anchor('login_sample/create','アカウントの作成');?>
<br />
<?php echo anchor('login_sample/logout', 'ログアウト'); ?>
</body>
</html>

こんな感じにすることで、次のようにして管理画面に到達できます。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

CAPTCHA