使用PHP搭建个人网站 Step #1 (CodeIgniter 安装使用)

经过几天的考察,决定采用 CodeIgniter 作为我的基础框架来使用,使用XMapp作为开发服务器。

1. CodeIgniter 的安装

没啥好说的,下载,解压缩

2. 配置

简单配置:要打开apache的RewriteEngine。

另外为了方便调试以及以后的部署,我在xmapp上配置了一个虚拟站点。

3. Getting Started

配置成功之后,使用浏览器访问本地服务器,第一个Demo页面出来了。根据以前学asp.net mvc的经验,先进到application/controllers/ 目录下,修改Welcome.php,在其中加入了一个hello的action。测试访问的时候,发现了一点点小问题:

使用 http://localhost/index.php/Welcome/hello 能够正确访问,但是不能使用 http://localhost/Welcome/hello 进行访问,这可不是典型的mvc格式。好吧,google..

在用户指南中发现了解决办法,在网站根目录下做一个 .htaccess文件就ok了,内容如下:

------------

Removing the index.php file

By default, the index.php file will be included in your URLs:
默认的,index.php会包含在URL中:

example.com/index.php/news/article/my_article

You can easily remove this file by using a .htaccess file with some simple rules. Here is an example of such a file, using the "negative" method in which everything is redirected except the specified items:
可以使用一个 .htaccess文件,写几个简单的规则就可以去掉index.php了

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

这个配置规则,将所有的请求都转到index.php了。当然为了网站能正常访问,还要进行例外配置的,例如要将 /images/, /styles/, /scripts/ 等目录例外,否则都引用不了这些元素。这个配置规则就不详细讲了。

现在再访问 http://localhost/Welcome/hello 能够正常访问了。

--------------------------

接下来,准备学习载入页面。CodeIgniter 是没有模板引擎的,所以,还得面对最常用的php应用方式。

1)新建Controller

在 application/controllers目录下新建 blogs.php,

<?php

class Blogs extends CI_Controller {

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

    }
}

Controller需要从 CI_Controller继承,View就是这个Controller中的Action了,这中间可以写各种操作,然后把数据返回给页面就可以了。

2)创建模板页

在application/views/下创建 template目录,再创建 header.php 与 footer.php,内容很简单,不多说。

3)创建内容页

在 application/views/目录下创建 blogs目录,再创建 view.php,然后在其中插入一些静态内容

<h2> <?php  echo($title)  ?> </h2>

4) 完成action代码

public function view($page = 'view')
{$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);
}

完成之后,即可使用  http://locahost/blogs/view 访问该页面,至此,静态页载入完成。这个load header与footer代码看来基本每个action都要写了,还真是累赘。。这就是没有页面模板引擎的弊端。

----------------------------------------------------------------------------------

接下来,完成初步的页面设计,并融入模板,下一步该是数据库的操作了,keep going!

原文地址:https://www.cnblogs.com/mobwiz/p/2981130.html