Kohana框架的安装及部署

Kohana框架的安装及部署

tips

kohana官网:https://kohanaframework.org/

kohana中文文档:https://github.com/stenote/Kohana_Docs_zh_CN/tree/master

Kohana安装以及部署

在官网下载kohana压缩包,解压到自己web项目目录下

kohana框架是一个轻量级的PHP开发框架,包结构主要分为4个部分:

  • application目录:应用程序的主要目录,包含了控制器、模型、视图和其他自定义代码文件。
  • system目录:这是Kohana框架的核心目录,包含了框架的各种类和库文件。通常不需要修改这些文件,除非你有特定的需求。
  • modules目录:这个目录用于存放可重用的模块。每个模块都可以有自己的MVC结构,类似于应用程序的结构。
  • public目录:这是Web服务器的根目录,其中包含了入口文件index.php和一些静态资源文件,如CSS、JavaScript和图片等。

1、重要文件作用说明

  • /index.php

index.php:这是Kohana应用程序的入口文件,位于public目录下。当Web服务器接收到请求时,会将请求交给index.php处理。该文件负责初始化框架并调度请求到相应的控制器和动作。它通常包含一些必要的设置和引入bootstrap.php文件的代码。

index.php是Kohana应用程序的入口文件,用于处理请求和调度控制器

  • /install.php

install.php:这是一个安装脚本,用于在初始部署时设置Kohana框架。它位于系统目录下,主要用于执行一些初始化操作,如创建数据库表、设置文件权限等。一旦完成安装过程,通常建议删除或禁用install.php文件,以防止未经授权的访问。

install.php是一个安装脚本,用于执行初始设置和配置。

  • /application/bootstrap.php

在Kohana框架中,bootstrap.php是一个重要的文件,它位于系统目录下。这个文件主要用于初始化框架和应用程序的各种设置。

在bootstrap.php文件中,你可以进行以下操作:

  1. 定义常量:你可以定义一些全局常量,如应用程序的根目录路径、环境变量等。
  2. 加载必要的文件:bootstrap.php会加载一些必要的文件,包括Autoloader类、Exception处理类等。
  3. 配置框架:你可以设置框架的各种配置选项,如默认时区、错误报告级别、数据库连接等。
  4. 注册模块:如果你使用了额外的模块,你可以在这里注册它们,以便框架能够正确加载和使用它们。
  5. 运行应用程序:最后,bootstrap.php会运行应用程序,启动请求处理流程,并将控制权交给应用程序的入口文件index.php。
  6. 配置路由规则,映射controller下的接口

bootstrap.php文件负责初始化框架和应用程序的各种设置,为应用程序的正常运行做好准备工作。

1.1 /index.php

php 复制代码
<?php

// application模块的包名
$application = 'application';

// modules模块的包名
$modules = 'modules';

// system模块的包名
$system = 'system';

// 定义EXT为.php,即PHP文件后缀
define('EXT', '.php');

// 设置错误报告级别为全部:严重错误、警告、通知,严格编码规范及最佳实践
error_reporting(E_ALL | E_STRICT);




// 定义常量DOCROOT 为 /,即全路径为根路径/
// Set the full path to the docroot
define('DOCROOT', realpath(dirname(__FILE__)).DIRECTORY_SEPARATOR);

// 校验包路径是否为文件夹
// Make the application relative to the docroot, for symlink'd index.php
if ( ! is_dir($application) AND is_dir(DOCROOT.$application))
	$application = DOCROOT.$application;

// Make the modules relative to the docroot, for symlink'd index.php
if ( ! is_dir($modules) AND is_dir(DOCROOT.$modules))
	$modules = DOCROOT.$modules;

// Make the system relative to the docroot, for symlink'd index.php
if ( ! is_dir($system) AND is_dir(DOCROOT.$system))
	$system = DOCROOT.$system;

// Define the absolute paths for configured directories
// 为配置好的包定义全路径常量名,即APPPATh为application包的全路径,MODPATH为modules包的全路径,SYSPATH为system包的全路径
define('APPPATH', realpath($application).DIRECTORY_SEPARATOR);
define('MODPATH', realpath($modules).DIRECTORY_SEPARATOR);
define('SYSPATH', realpath($system).DIRECTORY_SEPARATOR);

// Clean up the configuration vars
// 清除变量
unset($application, $modules, $system);

// 判断install.php文件是否存在,如果存在,则引入
if (file_exists('install'.EXT))
{
	// Load the installation check
	return include 'install'.EXT;
}
// 设置应用的启动时间常量
/**
 * Define the start time of the application, used for profiling.
 */
if ( ! defined('KOHANA_START_TIME'))
{
	define('KOHANA_START_TIME', microtime(TRUE));
}

/**
 * Define the memory usage at the start of the application, used for profiling.
 */
// 设置当前系统内存使用情况常量
if ( ! defined('KOHANA_START_MEMORY'))
{
	define('KOHANA_START_MEMORY', memory_get_usage());
}

// 引入bootstrap文件(重要)
// Bootstrap the application
require APPPATH.'bootstrap'.EXT;

// 判断当前运行环境是否是命令行环境,根据环境运行应用程序
if (PHP_SAPI == 'cli') // Try and load minion
{
	class_exists('Minion_Task') OR die('Please enable the Minion module for CLI support.');
	set_exception_handler(array('Minion_Exception', 'handler'));

    // 执行命令行任务
	Minion_Task::factory(Minion_CLI::options())->execute();
}
else
{
	/**
	 * Execute the main request. A source of the URI can be passed, eg: $_SERVER['PATH_INFO'].
	 * If no source is specified, the URI will be automatically detected.
	 */
	echo Request::factory(TRUE, array(), FALSE)// 创建请求对象,用于处理HTTP请求
        // 把请求处理结果输出到浏览器
		->execute()
		->send_headers(TRUE)
		->body();
}

1.2 /application/bootstrap.php

php 复制代码
<?php defined('SYSPATH') or die('No direct script access.');

// -- Environment setup --------------------------------------------------------

// Load the core Kohana class
// 加载kohana的核心库
require SYSPATH.'classes/Kohana/Core'.EXT;

// 在application包下或者system包下引入Kohana.php文件
if (is_file(APPPATH.'classes/Kohana'.EXT))
{
	// Application extends the core
	require APPPATH.'classes/Kohana'.EXT;
}
else
{
	// Load empty core extension
	require SYSPATH.'classes/Kohana'.EXT;
}

/**
 * Set the default time zone.
 *
 * @link http://kohanaframework.org/guide/using.configuration
 * @link http://www.php.net/manual/timezones
 */
// 设置默认时区
date_default_timezone_set('America/Chicago');

/**
 * Set the default locale.
 *
 * @link http://kohanaframework.org/guide/using.configuration
 * @link http://www.php.net/manual/function.setlocale
 */
// 设置语言环境
setlocale(LC_ALL, 'en_US.utf-8');

/**
 * Enable the Kohana auto-loader.
 *
 * @link http://kohanaframework.org/guide/using.autoloading
 * @link http://www.php.net/manual/function.spl-autoload-register
 */
// 允许kohana的自动加载器
spl_autoload_register(array('Kohana', 'auto_load'));

/**
 * Optionally, you can enable a compatibility auto-loader for use with
 * older modules that have not been updated for PSR-0.
 *
 * It is recommended to not enable this unless absolutely necessary.
 */
//spl_autoload_register(array('Kohana', 'auto_load_lowercase'));

/**
 * Enable the Kohana auto-loader for unserialization.
 *
 * @link http://www.php.net/manual/function.spl-autoload-call
 * @link http://www.php.net/manual/var.configuration#unserialize-callback-func
 */
ini_set('unserialize_callback_func', 'spl_autoload_call');

/**
 * Set the mb_substitute_character to "none"
 *
 * @link http://www.php.net/manual/function.mb-substitute-character.php
 */
mb_substitute_character('none');

// -- Configuration and initialization -----------------------------------------

/**
 * Set the default language
 */
I18n::lang('en-us');

if (isset($_SERVER['SERVER_PROTOCOL']))
{
	// Replace the default protocol.
	HTTP::$protocol = $_SERVER['SERVER_PROTOCOL'];
}

/**
 * Set Kohana::$environment if a 'KOHANA_ENV' environment variable has been supplied.
 *
 * Note: If you supply an invalid environment name, a PHP warning will be thrown
 * saying "Couldn't find constant Kohana::<INVALID_ENV_NAME>"
 */
//设置kohana的环境常量
if (isset($_SERVER['KOHANA_ENV']))
{
	Kohana::$environment = constant('Kohana::'.strtoupper($_SERVER['KOHANA_ENV']));
}

/**
 * Initialize Kohana, setting the default options.
 *
 * The following options are available:
 *
 * - string   base_url    path, and optionally domain, of your application   NULL
 * - string   index_file  name of your index file, usually "index.php"       index.php
 * - string   charset     internal character set used for input and output   utf-8
 * - string   cache_dir   set the internal cache directory                   APPPATH/cache
 * - integer  cache_life  lifetime, in seconds, of items cached              60
 * - boolean  errors      enable or disable error handling                   TRUE
 * - boolean  profile     enable or disable internal profiling               TRUE
 * - boolean  caching     enable or disable internal caching                 FALSE
 * - boolean  expose      set the X-Powered-By header                        FALSE
 */
Kohana::init(array(
	'base_url'   => '/',
));

/**
 * Attach the file write to logging. Multiple writers are supported.
 */
Kohana::$log->attach(new Log_File(APPPATH.'logs'));

/**
 * Attach a file reader to config. Multiple readers are supported.
 */
Kohana::$config->attach(new Config_File);

/**
 * Enable modules. Modules are referenced by a relative or absolute path.
 */
// 引入其他模块
Kohana::modules(array(
	 'auth'       => MODPATH.'auth',       // Basic authentication
	 'cache'      => MODPATH.'cache',      // Caching with multiple backends
	 'codebench'  => MODPATH.'codebench',  // Benchmarking tool
	 'database'   => MODPATH.'database',   // Database access
	 'image'      => MODPATH.'image',      // Image manipulation
	 'minion'     => MODPATH.'minion',     // CLI Tasks
	 'orm'        => MODPATH.'orm',        // Object Relationship Mapping
	 'unittest'   => MODPATH.'unittest',   // Unit testing
	 'userguide'  => MODPATH.'userguide',  // User guide and API documentation
	));

/**
 * Cookie Salt
 * @see  http://kohanaframework.org/3.3/guide/kohana/cookies
 * 
 * If you have not defined a cookie salt in your Cookie class then
 * uncomment the line below and define a preferrably long salt.
 */
// Cookie::$salt = NULL;
// 如果需要正常启动项目:需要给这个字段设置一个值(string),如Cookie::$salt = 'foobar';
/**
 * Set the routes. Each route must have a minimum of a name, a URI and a set of
 * defaults for the URI.
 */
// 设置接口的路由规则
Route::set('default', '(<controller>(/<action>(/<id>)))')
	->defaults(array(
		'controller' => 'welcome',
		'action'     => 'index',
	));

2、项目结构

3、路由配置

  • tip:在bootstrap.php文件中配置路由
  • my_app项目放在warmserver的www目录下
  • warmserver重新写虚拟映射之后,需要关闭warmserve再重新启动

3.1、隐藏项目入口的路由

​ kohana项目的入口是application目录下的index.php文件,因此如果需要访问项目的某个接口,需要先访问到项目入口index.php,这样在url上会显得不简洁,因此可以通过配置.htaccess文件,来隐藏url中默认的项目入口。把官网的kahana项目拉下来,项目根目录下会有默认的example.htaccess文件,把前缀名字去掉即可,即变成.htaccess

php 复制代码
eg:
前提:需要先使用nginx或者apache服务器映射项目路径跟本地的项目文件
    映射:http://my_app  =>  D:\PhpCode\kohana-demo
	D:\PhpCode\kohana-demo路径下即是官网拉下来的kohana项目,重新命名成了kohana-demo
配置前:
   	如果需要访问  http://localhost/my_app项目
	则需要输入url:http://localhost/my_app/index.php
注意:通过www目录映射的localhost访问www目录下的my_app项目时,url中的index.php不能省略,如http://localhost/my_app/index.php/   中的index.php/不能省略

3.2、配置默认路由

  • 需要注意拉下来的kohana项目默认配置了默认路由
  • 默认的路由配置需要在bootstrap.php文件的最下面,否则默认路由会匹配全部请求,就不会匹配到后面的路由了
  • 默认的路由映射,只要访问到该项目,即默认会路由到该接口,即访问到**/application/classes/Controller/welcome/index**
  • Controller/Welcome.php 文件下的action_index方法
  • 在bootstrap.php中配置
php+HTML 复制代码
Route::set('default', '(<controller>(/<action>(/<id>)))')
	->defaults(array(
		'controller' => 'welcome',
		'action'     => 'index',
	));
  • Controller/Welcome.php
php 复制代码
<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Welcome extends Controller {

	public function action_index()
	{
		$this->response->body('hello world');
	}

} // End Welcome
  • 访问默认的接口/Controller/Welcome/action_index
  • 访问默认的**/Controller/welcome/index**

3.3、配置自定义的路由(Controller目录下的控制器)

  • /Controller下创建myapi.php文件
php 复制代码
<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Myapi extends Controller {

    public function action_get_data()
    {
        $this->response->body('myapi');
    }
}
  • bootstrap.php中配置
php 复制代码
// 配置Controller下的某个控制器的路由
Route::set('myapi', 'myapi/<action>')
    ->defaults(array(
        'controller' => 'myapi',
        'action'     => 'index',
    ));

3.4、配置自定义的路由(Controller/directory下的控制器)

  • bootstrap.php中配置
php 复制代码
// 配置Controller目录下的某个文件夹下的控制器的路由
Route::set('api', 'api(/<controller>(/<action>))')
    ->defaults(array(
        'directory' => 'api',
        'controller' => 'default',
        'action' => 'index',
    ));
  • 创建Controller/api/game.php文件
php 复制代码
<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Api_Game extends Controller {

    public function action_get_data()
    {
        $this->response->body('game');
    }
}
相关推荐
BingoGo14 小时前
当你的 PHP 应用的 API 没有限流时会发生什么?
后端·php
JaguarJack14 小时前
当你的 PHP 应用的 API 没有限流时会发生什么?
后端·php·服务端
BingoGo2 天前
OpenSwoole 26.2.0 发布:支持 PHP 8.5、io_uring 后端及协程调试改进
后端·php
JaguarJack2 天前
OpenSwoole 26.2.0 发布:支持 PHP 8.5、io_uring 后端及协程调试改进
后端·php·服务端
JaguarJack3 天前
推荐 PHP 属性(Attributes) 简洁读取 API 扩展包
后端·php·服务端
BingoGo3 天前
推荐 PHP 属性(Attributes) 简洁读取 API 扩展包
php
JaguarJack4 天前
告别 Laravel 缓慢的 Blade!Livewire Blaze 来了,为你的 Laravel 性能提速
后端·php·laravel
郑州光合科技余经理4 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
QQ5110082854 天前
python+springboot+django/flask的校园资料分享系统
spring boot·python·django·flask·node.js·php
WeiXin_DZbishe4 天前
基于django在线音乐数据采集的设计与实现-计算机毕设 附源码 22647
javascript·spring boot·mysql·django·node.js·php·html5