kohana官网:https://kohanaframework.org/
kohana中文文档:https://github.com/stenote/Kohana_Docs_zh_CN/tree/master
在官网下载kohana压缩包,解压到自己web项目目录下
kohana框架是一个轻量级的PHP开发框架,包结构主要分为4个部分:
index.php:这是Kohana应用程序的入口文件,位于public目录下。当Web服务器接收到请求时,会将请求交给index.php处理。该文件负责初始化框架并调度请求到相应的控制器和动作。它通常包含一些必要的设置和引入bootstrap.php文件的代码。
index.php是Kohana应用程序的入口文件,用于处理请求和调度控制器
install.php:这是一个安装脚本,用于在初始部署时设置Kohana框架。它位于系统目录下,主要用于执行一些初始化操作,如创建数据库表、设置文件权限等。一旦完成安装过程,通常建议删除或禁用install.php文件,以防止未经授权的访问。
install.php是一个安装脚本,用于执行初始设置和配置。
在Kohana框架中,bootstrap.php是一个重要的文件,它位于系统目录下。这个文件主要用于初始化框架和应用程序的各种设置。
在bootstrap.php文件中,你可以进行以下操作:
bootstrap.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();
}
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::"
*/
//设置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', '((/(/)))' )
->defaults(array(
'controller' => 'welcome',
'action' => 'index',
));
kohana项目的入口是application目录下的index.php文件,因此如果需要访问项目的某个接口,需要先访问到项目入口index.php,这样在url上会显得不简洁,因此可以通过配置
.htaccess
文件,来隐藏url中默认的项目入口。把官网的kahana项目拉下来,项目根目录下会有默认的example.htaccess文件
,把前缀名字去掉即可,即变成.htaccess
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/不能省略
Route::set('default', '((/(/)))')
->defaults(array(
'controller' => 'welcome',
'action' => 'index',
));
defined('SYSPATH') or die('No direct script access.');
class Controller_Welcome extends Controller {
public function action_index()
{
$this->response->body('hello world');
}
} // End Welcome
defined('SYSPATH') or die('No direct script access.');
class Controller_Myapi extends Controller {
public function action_get_data()
{
$this->response->body('myapi');
}
}
// 配置Controller下的某个控制器的路由
Route::set('myapi', 'myapi/' )
->defaults(array(
'controller' => 'myapi',
'action' => 'index',
));
localhost => D:\Env\wamp64\www
myapp=>D:\Env\wamp64\www\my_app
// 配置Controller目录下的某个文件夹下的控制器的路由
Route::set('api', 'api(/(/))' )
->defaults(array(
'directory' => 'api',
'controller' => 'default',
'action' => 'index',
));
defined('SYSPATH') or die('No direct script access.');
class Controller_Api_Game extends Controller {
public function action_get_data()
{
$this->response->body('game');
}
}
localhost => D:\Env\wamp64\www
myapp=>D:\Env\wamp64\www\my_app