정적 페이지

Note: 이 튜토리얼은 당신이 CodeIgniter를 다운로드 및 개발 환경의 프레임워크를 설치 한 것으로 가정합니다.

처음으로 해야할 것은 정적 페이지를 처리하는 컨트롤러 를 설정하는 것입니다. 컨트롤러는 단순히 대표적인 일을 돕는 클래스입니다. 이것은 당신의 웹 어플리케이션의 접착제입니다.

예를 들면, 호출은:

http://example.com/news/latest/10

“news” 라는 이름의 컨트롤러가 있음을 상상할 수 있습니다. news 에서 호출되는 함수는 “latest” 일 것입니다. news 함수의 일은 10 개의 뉴스 아이템을 페이지에 렌더링합니다. MVC 에서 매우 자주, URL 패턴이 다음과 같이 매칭되는 것을 볼 수 있습니다:

http://example.com/[controller-class]/[controller-method]/[arguments]

URL 스키마가 더욱 복잡해지게 됨에 따라 이것은 변경될 수도 있습니다. 그러나 지금, 이것이 알아야할 전부입니다.

application/controllers/Pages.php 파일을 아래의 코드와 함께 생성해봅니다.

<?php
class Pages extends CI_Controller {

        public function view($page = 'home')
        {
        }
}

$page 라는 하나의 독립변수를 가지는 뷰 함수와 함께, “pages” 라는 이름의 클래스를 생성합니다. pages 클래스는 CI_Controller 클래스를 확장합니다. 이것은 새로운 pages 클래스가 CI_Controller 클래스에서 정의된 함수와 변수에 접근할 수 있다는 것을 의미합니다(system/core/Controller.php).

The controller is what will become the center of every request to your web application. In very technical CodeIgniter discussions, it may be referred to as the super object. Like any php class, you refer to it within your controllers as $this. Referring to $this is how you will load libraries, views, and generally command the framework.

Now you’ve created your first method, it’s time to make some basic page templates. We will be creating two “views” (page templates) that act as our page footer and header.

Create the header at application/views/templates/header.php and add the following code.

<html>
        <head>
                <title>CodeIgniter 튜토리얼(Tutorial)</title>
        </head>
        <body>

                <h1><?php echo $title ?></h1>

The header contains the basic HTML code that you’ll want to display before loading the main view, together with a heading. It will also output the $title variable, which we’ll define later in the controller. Now create a footer at application/views/templates/footer.php that includes the following code:

                <em>&copy; 2014</em>
        </body>
</html>

Adding logic to the controller

Earlier you set up a controller with a view() method. The method accepts one parameter, which is the name of the page to be loaded. The static page templates will be located in the application/views/pages/ directory.

In that directory, create two files named home.php and about.php. Within those files, type some text − anything you’d like − and save them. If you like to be particularly un-original, try “Hello World!”.

In order to load those pages, you’ll have to check whether the requested page actually exists:

public function view($page = 'home')
{
        if ( ! file_exists(APPPATH.'views/pages/'.$page.'.php'))
        {
                // Whoops, we don't have a page for that!
                show_404();
        }

        $data['title'] = ucfirst($page); // Capitalize the first letter

        $this->load->view('templates/header', $data);
        $this->load->view('pages/'.$page, $data);
        $this->load->view('templates/footer', $data);
}

Now, when the page does exist, it is loaded, including the header and footer, and displayed to the user. If the page doesn’t exist, a “404 Page not found” error is shown.

The first line in this method checks whether the page actually exists. PHP’s native file_exists() function is used to check whether the file is where it’s expected to be. show_404() is a built-in CodeIgniter function that renders the default error page.

In the header template, the $title variable was used to customize the page title. The value of title is defined in this method, but instead of assigning the value to a variable, it is assigned to the title element in the $data array.

The last thing that has to be done is loading the views in the order they should be displayed. The second parameter in the view() method is used to pass values to the view. Each value in the $data array is assigned to a variable with the name of its key. So the value of $data['title'] in the controller is equivalent to $title in the view.

Routing

The controller is now functioning! Point your browser to [your-site-url]index.php/pages/view to see your page. When you visit index.php/pages/view/about you’ll see the about page, again including the header and footer.

Using custom routing rules, you have the power to map any URI to any controller and method, and break free from the normal convention: http://example.com/[controller-class]/[controller-method]/[arguments]

Let’s do that. Open the routing file located at application/config/routes.php and add the following two lines. Remove all other code that sets any element in the $route array.

$route['default_controller'] = 'pages/view';
$route['(:any)'] = 'pages/view/$1';

CodeIgniter reads its routing rules from top to bottom and routes the request to the first matching rule. Each rule is a regular expression (left-side) mapped to a controller and method name separated by slashes (right-side). When a request comes in, CodeIgniter looks for the first match, and calls the appropriate controller and method, possibly with arguments.

More information about routing can be found in the URI Routing documentation.

Here, the second rule in the $routes array matches any request using the wildcard string (:any). and passes the parameter to the view() method of the pages class.

Now visit index.php/about. Did it get routed correctly to the view() method in the pages controller? Awesome!