在 PHP 中向实例添加对象

发布于 2024-10-20 20:58:53 字数 1337 浏览 1 评论 0原文

简介

我正在开发一个 MVC 框架,但遇到了一个问题。看来我试图完成的事情被称为单例设计方法——仅初始化类一次。请记住,我试图在控制器“acontroller”中放置尽可能少的代码。

话虽如此,最后一个问题仍然是:如何将对象添加到已实例化的对象中?

拥有或至少看到实际源而不是示例源可能会有所帮助,所以我有将我的源代码推送到我的 github 上。您可以在这里找到:https://github.com/derekmaciel/uMVC


代码说明

“发生了什么” the hood”是第一个,

  • Controller 类加载位于 /application/controller 中的控制器,在本例中为“acontroller”。
  • 之后,acontroller 类使用 Load 类加载模型(称为“amodel”),使用 $this->load->model("amodel"),该模型在 Controller __construct 中实例化。
  • $this->load->model("amodel") 最终的结果是: $controller->amodel => new Amodel(),其中 $controller 是控制器实例(不是控制器,因为加载模型的控制器会有所不同)。
  • 步骤 4:允许控制器访问已加载的模型 (amodel)。

代码结果

这些脚本的当前输出的副本可以在此处找到:http://pastebin.com/EJxuXaki

您会注意到的第一件事是,我因使用已弃用的分配而收到警告。我现在将重点关注错误。

您会注意到的第二件事是我首先 print_r() 了 Controller 实例。里面有一个模型对象,要添加到控制器中。

之后,我 print_r() 了 $this (acontroller) 对象。它拥有从 __construct() 获得的所有内容,但没有模型。

如果我能让控制器“看到”模型,那么我的问题就会得到解决。

另外: 我是否可以从控制器 acontroller 中删除“parent::init()”?我这样做只是为了让控制器可以访问 Load 和 Model 类,但我试图在控制器中放置尽可能少的代码,因此让控制器自动访问 Load 和 Model 会有很大帮助。

我希望我说清楚了。感谢您的帮助

Intro

I'm developing an MVC framework, and I've run into a problem. It seems what I was trying to accomplish is known as the Singleton Design method -- initializing classes only once. Remember that I'm trying to put as less code in the controller "acontroller" as possible.

With that said, a final question remains: how can I add objects to an object that has already been instantialized?

It may help to have or at least see actual source instead of just example source, so I have pushed my source to my github. You can find that here: https://github.com/derekmaciel/uMVC


Code explanation

What's happening "under the hood" is first,

  • The Controller class loads a controller located in /application/controller, in this case "acontroller".
  • After, the acontroller class loads a model (called "amodel") using the Load class, using $this->load->model("amodel"), which was instantialized in the Controller __construct.
  • The final outcome of $this->load->model("amodel") is: $controller->amodel =& new Amodel(), where $controller is the Controller instance (not acontroller, because the controller loading the model will vary).
  • Step 4: Allow acontroller access to models that were loaded (amodel).

Code result

A copy of the current output of these scripts can be found here: http://pastebin.com/EJxuXaki

The first thing you'll notice is that I'm given a warning for using a deprecated assignment. I'm going to focus on the error for now.

The second thing you'll notice is that I first print_r()'d the Controller instance. Inside there is an amodel object, which is want to add to acontroller.

After that, I print_r()'d the $this (acontroller) object. It has everything it got from __construct(), but not amodel.

If I can get acontroller to "see" amodel, then my problem will be solved.

Also:
Is there anyway for me to remove "parent::init()" from the controller acontroller? I only did that so acontroller could have access to both the Load and Model class, but I'm trying to put as less code as possible in acontroller, so having the acontroller have access to Load and Model automatically would help a lot.

I hope I was clear. Thanks for any help

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

千寻… 2024-10-27 20:58:53

我个人不认为单例方法属于 MVC 框架,原因是加载的主要对象是模型、库和控制器,其他所有对象(例如路由器)通常都是硬编码的。

我要做的结构是创建以下类:

  • ModelLoader
  • LibraryLoader

并在系统启动期间包含它们,然后在主控制器中执行以下操作:

class Controller
{
    public $library;
    public $model;

    public function __construct()
    {
        $this->library = new LibraryLoader();
        $this->model = new ModelLoader();
    }
}

这会将 2 个加载器暴露给子控制器,您的模型/库应该拥有一个私有的存储加载对象的数组,有点像这样:

class LibraryLoader extends ObjectLoader
{
     protected $_path = "/app/library/";
     protected $_ext = '.php';
}

class ModelLoader extends ObjectLoader
{
     protected $_path = "/app/models/";
     protected $_ext = '.php';
}

对象加载器看起来像这样:

class ObjectLoader
{
     protected $_path = "/app/";
     protected $_ext = '.php';

     public function __get($item)
     {
          /*
                * Load item here, the paths above would be overwritten
                * store the object in an array, make sure you check if its already loaded
           */
     }
}

这是非常基本的,但是在您的子控制器(例如索引/主页等)中,您可以执行以下操作:

class indexController extends Controller
{
    public function index()
    {
        $this->model->users->getUser(22);
        $this->library->security->validateInput("get","key");

        //As the objectLoader manages whats loaded, any further calls to the above would
        //use the same objects initiated as above.
    }
}

这应该让您开始,它更多使用单例方法简化它们。

I personally do not think that singleton methods belong within an MVC Framework, the reason for this is because the main objects that are loaded are Models,Libraries and controllers, everything else such as the Router is usually hard coded.

The structure that i would do is create the following classes:

  • ModelLoader
  • LibraryLoader

and have them included during system boot, then within your main controller do the following:

class Controller
{
    public $library;
    public $model;

    public function __construct()
    {
        $this->library = new LibraryLoader();
        $this->model = new ModelLoader();
    }
}

this would expose the 2 loaders to the child controller, your model/library should hold a private array storing the loaded objects, a little something like this:

class LibraryLoader extends ObjectLoader
{
     protected $_path = "/app/library/";
     protected $_ext = '.php';
}

class ModelLoader extends ObjectLoader
{
     protected $_path = "/app/models/";
     protected $_ext = '.php';
}

the object loader would look like so:

class ObjectLoader
{
     protected $_path = "/app/";
     protected $_ext = '.php';

     public function __get($item)
     {
          /*
                * Load item here, the paths above would be overwritten
                * store the object in an array, make sure you check if its already loaded
           */
     }
}

this is pretty basic, but within your child controllers such as index / home etc you can do the following:

class indexController extends Controller
{
    public function index()
    {
        $this->model->users->getUser(22);
        $this->library->security->validateInput("get","key");

        //As the objectLoader manages whats loaded, any further calls to the above would
        //use the same objects initiated as above.
    }
}

This should get you started, its more streamline them using the singleton approach.

荒路情人 2024-10-27 20:58:53

我想您需要在controller.php 中包含Model.php 才能使用模型类。

include 'Model.php';
include 'Load.php';

I guess you need to include Model.php in your controller.php to be able to use model class.

include 'Model.php';
include 'Load.php';
记忆里有你的影子 2024-10-27 20:58:53

从 PHP 5.3 开始,你可以使用 static 关键字来实例化一个类

abstract class singleton
{
    /**
     * Holds an insance of self
     * @var $instance
     */
    protected static $instance = NULL;

    /**
     * Prevent direct object creation
     */
    final private function  __construct() { }

    /**
     * Prevent object cloning
     */
    final private function  __clone() { }

    final public static function getInstance()
    {
        if(null !== static::$instance){
            return static::$instance;
        }
        static::$instance = new static();
        return static::$instance;
    }
}

class myclass extends singleton
{
}

$myclass = myclass::getInstance();

Since PHP 5.3 you can use the static keyword to instantiate a class

abstract class singleton
{
    /**
     * Holds an insance of self
     * @var $instance
     */
    protected static $instance = NULL;

    /**
     * Prevent direct object creation
     */
    final private function  __construct() { }

    /**
     * Prevent object cloning
     */
    final private function  __clone() { }

    final public static function getInstance()
    {
        if(null !== static::$instance){
            return static::$instance;
        }
        static::$instance = new static();
        return static::$instance;
    }
}

class myclass extends singleton
{
}

$myclass = myclass::getInstance();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文