Created
June 6, 2011 11:12
-
-
Save favrik/1010076 to your computer and use it in GitHub Desktop.
A CodeIgniter controller used for static sites
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| class Staticx extends CI_Controller { | |
| /** | |
| * This action must be configured as a "catch-all" url inside | |
| * application/config/routes.php You can do this by adding the following | |
| * line to that file: | |
| * | |
| * $route['(:any)'] = 'staticx/route/$1'; | |
| */ | |
| public function route() { | |
| $page_data = array(); | |
| if ($page = $this->_is_route_valid(func_get_args())) { | |
| $page_data = $this->_get_page_data($page) + array( | |
| 'view' => $this->load->view($page, '', true) | |
| ); | |
| } | |
| $this->load->view('layout', $page_data); | |
| } | |
| /** | |
| * Here you can define the variables you want to be able to define in your | |
| * view files, and use in your layout file. | |
| */ | |
| public function get_available_page_data() { | |
| return array( | |
| 'page_title' => 'Page Title', | |
| 'meta_keywords' => 'Meta Keywords', | |
| ); | |
| } | |
| /** | |
| * Verifies that a view file exists for the path called. | |
| * | |
| * @param array $route - The arguments passed to the route() method | |
| * @return mixed string or false if route is invalid | |
| */ | |
| private function _is_route_valid($route) { | |
| $page = implode('/', $route); | |
| if (file_exists(APPPATH . "views/$page.php")) { | |
| return $page; | |
| } | |
| return FALSE; | |
| } | |
| /** | |
| * Inspired by/Taken from Wordpress function get_file_data() in wp-includes/functions.php | |
| * | |
| * @see http://codex.wordpress.org/File_Header | |
| */ | |
| private function _get_page_data($page) { | |
| $file_data = $this->_get_file_data($page); | |
| $headers = $this->get_available_page_data(); | |
| foreach($headers as $field => $regex) { | |
| preg_match('/^[ \t\/*#]*' . preg_quote($regex, '/') . ':(.*)$/mi', $file_data, ${$field}); | |
| if ( ! empty(${$field})) { | |
| ${$field} = $this->_cleanup_header_comment(${$field}[1]); | |
| } else { | |
| ${$field} = ''; | |
| } | |
| } | |
| return compact(array_keys($headers)); | |
| } | |
| private function _get_file_data($page) { | |
| $fp = fopen(APPPATH . "views/$page.php", 'r'); | |
| $file_data = fread($fp, 8192); | |
| fclose($fp); | |
| return $file_data; | |
| } | |
| /** | |
| * Inspired by/Taken from Wordpress; in wp-includes/functions.php | |
| * | |
| * @param string $str | |
| * @return string | |
| */ | |
| private function _cleanup_header_comment($str) { | |
| return trim(preg_replace("/\s*(?:\*\/|\?>).*/", '', $str)); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment