How to delete a PHP object from its class?

后端 未结 7 892
攒了一身酷
攒了一身酷 2021-01-02 06:51

I know that for some that might sound stupid, but I was thinking if I hava a delete() method in a class that removes all the object data (from DB and file system), how can I

7条回答
  •  盖世英雄少女心
    2021-01-02 07:11

    I'm in this same boat now.

    I'm building a CMS solution from the ground up and have a lot of references between objects; users, groups, categories, forums, topics, posts, etc.

    I also use an "Object::getObject(id)" loader in each class which ensures there's only one instance of an object per ID, but also means it's even easier for code to pull a reference to existing objects.

    When the data the object represents gets deleted from the data source, I'd like to wipe the object from memory and nullify all references to it to ensure other code doesn't try to use an obsolete data set.

    Ideally all references should be removed--the referencing code can provide a callback that gets fired at object deletion that can subsequently remove/update the reference. But if the referencing code gets sloppy, I'd rather it error out with a "Not an object" error than actually work with the object.

    Without knowing how to force the destruction from within the object, itself, I'm being forced to:

    1. Begin almost every non-static method with a check to see if the object has been flagged "deleted", throwing an exception if it is. This ensures any referencing code can't do any harm, but it's a nasty thing to look at in the code.

    2. Unset every object variable after deletion from the database, so it doesn't linger in memory. Not a big deal but, again: nasty to look at.

    Neither would be needed if I could just destroy the object from within.

提交回复
热议问题