【问题标题】:Refactoring require_once file in a project在项目中重构 require_once 文件
【发布时间】:2011-10-16 14:56:04
【问题描述】:

我是 PHP 的初学者。我正在处理具有此目录层次结构的项目:modelcontrolviewhelper 文件夹在我的项目文件夹中

现在我正在尝试在每个controlmodel 文件中写入一个文件init.phprequire_once,这是我的init.php

<?php

    $current_dir = basename(getcwd());
    $model_dir = "model";
    $helper_dir = "helper";

    function require_helper(){
        $handle = opendir("../{$helper_dir}");
        while($file = readdir($handle)){
        if($file != "." && $file != ".."){
                require_once "../{$helper_dir}/{$file}";
            }
        }
    }

    if($current_dir == "control"){
        $handle = opendir("../{$model_dir}");
        while($file = readdir($handle)){
            if($file != "." && $file != ".."){
                require_once "../{$model_dir}/{$file}";
            }
        }

        require_helper();

    } elseif( $current_dir == "model") {
        $handle = opendir($current_dir);
        while($file = readdir($handle)){
            if($file != "." && $file != ".."){
                require_once "{$file}";
            }
        }

        require_helper();
    } 
?>

但是当我测试我的项目时,我得到了这个错误:

注意:未定义变量:第 11 行 C:\wamp\www\harmony\control\login.php 中的会话

这是我的login.php 文件:

<?php
    require_once "../helper/init.php";
?>

<?php

    if(isset($_GET["logout"]) && $_GET["logout"] == "true" ){
        $session->logout();
    }

    if($session->is_logged_in()){
        redirect_to("../view/index.php"); 
    }

    if(isset($_POST["submit"])){
        $username = $db->escape_value($_POST["username"]);
        $password = $db->escape_value($_POST["password"]);
        $password = hash('sha1' , $password);
        $arr = User::auth($username , $password);
        if($arr){
            $usr = $db->instantiate($arr);            
            $session->login($usr);
        } else {
            Session::notify("Invalid login information.");
        }
    }    

?>

那么你能帮帮我吗?怎么了?

【问题讨论】:

  • 尝试将 if(isset($session) && $session->is_logged_in()){ 添加到该条件。这应该可以消除错误。
  • 在所有文件中请求init.php?你这样做是错的!查找front controller 设计。基本上,您应该拥有一个处理所有请求并加载必要文件的文件。这大大减少了重复样板代码的数量。
  • @Mchl 你能给我一个好的前端控制器设计的php教程吗?谢谢:)
  • 并非如此。我还没有写一个;P 然而,我的想法是让你的 index.php 根据 URL 参数(进入 $_GET 数组)决定需要和执行哪些文件/类。我研究的所有 PHP MVC 框架都使用该方案的变体。
  • 哦,所以我可以修改init.php,这样我就可以使用 $_GET 变量了吗?或者只需要重新开始。

标签: php refactoring undefined require-once


【解决方案1】:

您正在尝试访问函数内部的 $current_dir、$model_dir 和 $helper_dir。您不能访问在函数外部声明的变量,除非它们被声明为全局变量,或者实际传递给函数。

例如:

function require_helper(){
    global $helper_dir;//this is key
    $handle = opendir("../{$helper_dir}");
    while($file = readdir($handle)){
    if($file != "." && $file != ".."){
            require_once "../{$helper_dir}/{$file}";
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-23
    • 1970-01-01
    • 2017-04-29
    • 2011-04-13
    • 2014-08-14
    • 1970-01-01
    • 2013-06-11
    • 2019-11-21
    相关资源
    最近更新 更多