phalcon使用命名空间

直接通过是代码来演示

目录结构

项目名称是zhaofangapi

zhaofangapi
    app
        backend
            controllers
                ControllersBase.php
                IndexController.php
            models
        common
            controllers
            models
            utils
                CFunc.php
        config
            config.php
            loader.php
            router.php
            service.php
        frontend
            controllers
            models
        library
        migrations
        tasks
        views
        cli.php
    cache
    public
        css
        files
        img
        js
        temp
        .htaccess
        index.php
        webtools.config.php
        webtools.php
    .htaccess
    .htrouter.php
    index.html
    README.md

config.php

<?php
/*
 * Modified: prepend directory path of current file, because of this file own different ENV under between Apache and command line.
 * NOTE: please remove this comment.
 */
defined('BASE_PATH') || define('BASE_PATH', getenv('BASE_PATH') ?: realpath(dirname(__FILE__) . '/../..'));
defined('APP_PATH') || define('APP_PATH', BASE_PATH . '/app');

return new \Phalcon\Config([
    'database' => [
        'adapter'     => 'Mysql',
        'host'        => 'localhost',
        'username'    => 'root',
        'password'    => '',
        'dbname'      => 'house',
        'charset'     => 'utf8',
    ],
    'application' => [
        'appDir'         => APP_PATH . '/',
//        'controllersDir' => APP_PATH . '/controllers/',
//        'modelsDir'      => APP_PATH . '/models/',
        'migrationsDir'  => APP_PATH . '/migrations/',
        'viewsDir'       => APP_PATH . '/views/',
        'pluginsDir'     => APP_PATH . '/plugins/',
        'libraryDir'     => APP_PATH . '/library/',
        'cacheDir'       => BASE_PATH . '/cache/',

        // This allows the baseUri to be understand project paths that are not in the root directory
        // of the webpspace.  This will break if the public/index.php entry point is moved or
        // possibly if the web server rewrite rules are changed. This can also be set to a static path.
        'baseUri'        => preg_replace('/public([\/\\\\])index.php$/', '', $_SERVER["PHP_SELF"]),
    ]
]);

loader.php

<?php

$loader = new \Phalcon\Loader();

/**
 * We're a registering a set of directories taken from the configuration file
 */
//$loader->registerDirs(
//    [
//        $config->application->controllersDir,
//        $config->application->modelsDir
//    ]
//)->register();

$loader->registerDirs(
    [
        //公共模块
        APP_PATH . '/common/utils/',
        APP_PATH . '/common/controllers/',
        APP_PATH . '/common/models/',
        //后端模块
        APP_PATH . '/backend/controllers/',
        APP_PATH . '/backend/models/',
        //前端模块
        APP_PATH.'/frontend/models/',
        APP_PATH.'/frontend/controllers/',
    ]
);
$loader->registerNamespaces([
    //公共模块
    'Common\Utils' =>APP_PATH.'/common/utils/',
    'Common\Controllers' =>APP_PATH.'/common/controllers/',
    'Common\Models' =>APP_PATH.'/common/models/',
    //后端模块
    'Home\Models' => APP_PATH.'/backend/models/',
//    'Home\Service' => APP_PATH.'/service/',
    'Home\Controllers' => APP_PATH.'/backend/controllers/',
    //front 前端模块
    'Front\Models' => APP_PATH.'/frontend/models/',
//    'Front\Service' => BASE_PATH.'/front/service/',
    'Front\Controllers' => APP_PATH.'/frontend/controllers/',
]);

$loader->register();

router.php

<?php

$router = $di->getRouter();

// Define your routes here

$router->handle();
$router->add('/:controller/:action/:params', [
    'namespace'=>"Home\Controllers",
    'controller' => 1,
    'action' => 2,
    'params' => 3
]);
$router->add('/front/:controller/:action/:params', [
    'namespace'=>"Front\Controllers",
    'controller' => 1,
    'action' => 2,
    'params' => 3
]);

service.php

追加以下代码

$di->set('dispatcher',function () use ($di){
    $dispatcher = new \Phalcon\Mvc\Dispatcher();
    $dispatcher->setDefaultNamespace('Home\Controllers');
    return $dispatcher;
});

ControllerBase.php

<?php
namespace Home\Controllers;
use Phalcon\Mvc\Controller;

class ControllerBase extends Controller
{

}

IndexCtroller.php

<?php
namespace Home\Controllers;
use Home\Controllers\ControllerBase;
use Common\Utils\CFunc;
class IndexController extends ControllerBase
{

    public function indexAction()
    {

    }
    public function textAction(){
        $ne = new CFunc();
        CFunc::returnjson('0','没有错误!你好世界!');
//        echo "hello world";
    }

}


CFunc.php

<?php
/**
 * Class CFunc 存放公共方法的类
 * @package app\common\utils
 */
namespace Common\Utils;
class CFunc{
    /**
     * @return array
     */
    public static function params(){
        $params = [];
        if($_REQUEST){
            $params = $_REQUEST;
        }
        return $params;
    }
    public static function returnjson($errCode = "0",$message = '',$arr = []){
        $res = [];
        $res['errCode'] = $errCode;
        $res['msg'] = $message;
        $res['data'] = $arr;
        $call = isset($_REQUEST['callback']) ? $_REQUEST['callback'] : '';
//         echo json_encode($res);
        echo $call."(".json_encode($res).")";
    }
    /**
     * @param $arr
     * @return array
     */
    public static function decode_params($arr){
        if(!is_array($arr)){
            echo '参数不合法';
            exit();
        }
        foreach ($arr as $k => $val){
            $arr[$k] =self::_decrypt($val);
        }
        return $arr;
    }
}

文档中使用说明

// 第一步:设置框架
$loader = new Loader();
$loader->registerNamespaces(array(
    'app\controllers' => '../app/controllers/',
    'app\models' => '../app/models/',
    // 按需设置多个
));
$loader->register();

//第二步:设置默认命名空间,不设置会出现无法加载的情况(有点不明白)
$di->set('dispatcher', function () use ($di) {
    $dispatcher = new \Phalcon\Mvc\Dispatcher();
    $dispatcher -> setDefaultNamespace('Home\Controllers');
    return $dispatcher;
});
// 控制器代码
<?php

namespace app\controllers;

use app\models\Users;
use Phalcon\Mvc\Controller;

class IndexController extends Controller
{
    public function IndexAction()
    {
        $user = new Users();
        echo '<h1>Hello!</h1>';
    }
}

// 模型代码
<?php

namespace app\models;

class Users
{

}

猜你喜欢

转载自blog.csdn.net/benben0729/article/details/87916202