One of my colleagues moved to a different company and I got his source code of an existing project.
I was shocked how messy the code looked. I am not a PHP developer so maybe this is a stupid question but it seems to me that he uses the $_SESSION too much and we get many errors regarding the Sessions. I was wondering if it would be good to encapsulate the $_SESSION and write for each value he uses an own method.
The problem I see with this code is that he uses the session object like this
$_SESSION['customer']['items'] = getItems() //returns an array
$_SESSION['article'][$Id]['name'] = utf8_decode[$received[1]];
So from my point of view I would store all his stuff in simple Popos and place those into the Session.
So the Popo for the customer would look like this
class CustomerPopo
{
private $_id;
private $_salutation;
private $_name;
private $_surename;
public function getId()
{
return $this->_id;
}
public function setId($value)
{
$this->_id = $value;
}
public function getSalutation()
{
return $this->_salutation;
}
public function setSalutation($value)
{
$this->_salutation = $value;
}
public function getName()
{
return $this->_name;
}
public function setName($value)
{
$this->_name = $value;
}
public function getSurename()
{
return $this->_surename;
}
public function setSurename($value)
{
$this->_surename = $value;
}
function CustomerPopo() {
}
}
And I imagined the SessionManager like this
class SessionManager
{
private static function getValue($valueName)
{
$value = SessionManager::getValueFromSession($valueName);
if (is_null($value)) {
//Handle stuff and do further checks
}
return $value;
}
private static function getValueFromSession($valueName)
{
$value = null;
if (isset($_SESSION[$valueName])) {
$value = $_SESSION[$valueName];
}
return $value;
}
private static function setValue($valueName, $value)
{
$_SESSION[$valueName] = $value;
}
private static function clearValue($valueName)
{
if (isset($_SESSION[$valueName])) {
unset($_SESSION[$valueName]);
}
}
public static function getCustomer()
{
$customer = '';
try {
$customer = SessionManager::getValue('customer');
} catch (Exception $e) {
$customer = '';
}
return $customer;
}
public static function setCustomer($customer)
{
SessionManager::setValue('customer', $customer);
}
}
With this I could kill some of the errors which arise from different spellings of the word customer/Customer/cusomter.
I imagine the SessionManager would grow big because we have ~30 Session variables in the code.
Is there a design pattern which I could follow to implement such a SessionManager without making it worse in the end ? as stated I am not very familiar with PHP (yet).
EDIT:
Since the approach seems to be valid how can I handle the 30 Session variables i mentioned ? If I have a set/get and maybe a clear method for each value i will end up with 60-90 methods
It is a good idea to have an object encapsulating the access to global variables such as $_SERVER, $_GET, $_POST or $_SESSION as in your example. It is common practice in MVC architecture to do so.
Should the class have methods for IDE completition? That is actually up to you, but common practice at workplaces where I worked was not to have them but make const string identifiers of the fields instead, which are then used to specifying the index in the global $_SESSION variable through an object, such as your SessionManager.
But even then, I would probably ditch the static methods and go with an instance of the manager instead. Having a class with static methods may prevent typos, but does not fix the global state issue, which can be a huge problem when unit testing your applicaion.
I absolutely agree that using the $_SESSION like your college did is messy, since you have a hard time to figure out what is actually stored in the session.
In my opinion, the CustomerPopo is a very good idea, since it is very easy to understand the available data. Also, an IDE will be able to understand it either and offer this information to you as code completion and checks.
I also like your SessionManager, but I would try to get rid of these getValue/setValue functions and move to move verbose functions like getCustomer/setCustomer.
I guess you are not using a PHP framework. I think you should have a look at them, they are very handy (for instance Symfony or Yii2).
One last thing: Always keep in mind that all data stored in the session object will be loaded and parsed for each request, nevertheless if you use it or not. So if you store a lot of data which you only just for specific request, you should consider using another place to store it, like an external cache.
Also, the Session introduces state, which you should avoid if any possible.
Related
Likely this has already been asked, but nevertheless, here goes. This may fall under best practice or security... I'm not really sure.
In my application, I am using a nested object, that is called in the __construct() function. Sort of like this:
class user {
public $userID = NULL;
public $someObject = NULL;
public function __construct() {
$this->userID = getThisUser();
$this->someObject = new objectBuilder($this->userID);
}
public function getThisUser() {
// ...
}
}
class objectBuilder {
public $buriedVar = NULL;
public function __construct($uid = NULL) {
if( !isset($uid) ) {
$this->buriedVar = setTheObject($uid);
} else {
$this->buriedVar = setTheObject(0);
}
}
public function setTheObject($id) {
// ...
return "random string";
}
}
$tom = new user();
Obviously terrible outline here, but the point is, I can then call $tom->someObject->buriedVar and it'll return "random string".
While looking for a way to nest classes, I noticed no one recommends this as a method for storing objects inside of another object. I'm curious of a few things:
1) Is this insecure?
2) Are the vars inside the nested object exclusive to the call made inside $tom->__construct(), or if I create another object using new objectBuilder() is it overwriting the one inside $tom->someObject? I haven't noticed this, but am not sure how to test for that entirely.
3) Is there something else I'm missing? A best practice reason not to instantiate an object inside a class? I've been using it for years and it works great for what I've done. Is it a speed thing?
1) Is this insecure?
Not inherently, no.
2) Are the vars inside the nested object exclusive to the call made
inside $tom->__construct(), or if I create another object using new
objectBuilder() is it overwriting the one inside $tom->someObject? I
haven't noticed this, but am not sure how to test for that entirely.
This is a fundamental question between class and object. Objects are instances of a class and there can be multiple. The only things that would be overwritten are static properties and methods. You could test it like this:
<?php
$obj1 = new objectBuilder();
$obj2 = new objectBuilder();
if ($obj1 !== $obj2) {
echo "objects are not the same\n";
}
if ($obj1->buriedVar !== $obj2->buriedVar) {
echo "nested objects are not the same either\n";
}
$obj3 = new objectBuilder(1);
if ($obj1->buriedVar != $obj3->buriedVar) {
echo "even the values of two different buried vars with different values are different.\n";
}
if ($obj1->buriedVar == $obj2->buriedVar) {
echo "counter-example: nested variables with the same values set are similar.\n";
}
It helps to know the difference between equality and identity (see this SO post).
3) Is there something else I'm missing? A best practice reason not to
instantiate an object inside a class? I've been using it for years and
it works great for what I've done. Is it a speed thing?
You touched on it briefly. What you should know is that this is not scalable and is difficult to test.
Imagine you're creating a website for dogs.
<?php
class Bio
{
public function __construct()
{
$this->dog = new Dog('Terrier');
}
}
class Dog
{
private $animal = 'dog';
private $noise = 'woof!';
private $breed;
public function __construct($breed=null)
{
$this->setBreed($breed);
}
public function setBreed($breed)
{
$this->breed = $breed;
}
}
What if you want to add a new breed? Well... That's easy enough:
class Bio
{
// ...
public function __construct($breed)
{
$this->dog = new Dog($breed);
}
// ...
}
Cool! You've solved everything.
Except...
One day you want to create a section for cats, because one of your best writers also loves cats, and you sense an untapped market.
Uh oh...
You can refactor the code, of course. But you wrote it a long time ago. Now you have to go in and figure out where everything went. No big deal.. A bit annoying but you fixed it!
But now you have another problem. Turns out that the same author wants to add different traits to the breed. You're surprised this hasn't come up sooner but, hey, it's probably a good thing to have.
Now you need to go in to the Dog object, and the Cat object, and add traits.
Every single time.
On. Every. Bio.
After some reconfiguring, you've created something monstrous like this:
$article1 = new Bio('Terrier', 'dog', ['independent']);
$article2 = new Bio('Persian', 'cat', ['flat-faced']);
//... and so on, and so on
The next time the author asks for something, you fire her and then tear your hair out in a mad rage.
Or, from the beginning, you use Dependency Injection.
<?php
class Bio
{
private $animal;
public function __construct(AnimalInterface $animal)
{
$this->animal = $animal;
}
}
interface Animal
{
public function getType();
public function setBreed($breed);
public function getBreed();
public function setTraits(array $traits);
public function getTraits();
}
abstract class AbstractAnimal implements AnimalInterface
{
private $breed;
private $traits = [];
abstract public function getType();
public function setBreed($breed)
{
$this->breed = $breed;
}
public function getBreed()
{
return $this->breed;
}
public function setTraits(array $traits)
{
$this->traits = $traits;
}
public function getTraits()
{
return (array)$this->traits;
}
}
class Cat extends AbstractAnimal
{
public function getType()
{
return 'cat';
}
}
class Dog extends AbstractAnimal
{
public function getType()
{
return 'dog';
}
}
This pattern requires little to no editing after it has been created.
Why? Because you are injecting the object to nest into the class, rather than instantiating it in the object.
$bio1 = new Bio($dog); $bio2 = new Bio($cat); can always stay like this. Now you just edit the $dog and $cat objects. The added benefit is that these objects can be used anywhere.
But what about utility classes?
(This is where testability comes in. If you haven't worked with unit testing, I recommend reading up on it in the link to PHPUnit below. I'm not going to dwell on how that works as it's off topic).
Dependency Injection is well and good if you have classes that require customization. But what about utility classes that just house various functions?
class Utils
{
public function add($a, $b)
{
return $a + $b;
}
}
You might think that you can call this function safely from the constructor. And you can. However, one day you might create a log method in your Utils class:
public function log($msg)
{
exec("cat '$msg' > /tmp/log.txt");
}
This works just fine. However, when you run tests, your /tmp/log.txt file complains. "Invalid permissions!". When this method is run via your website, log.txt needs to be writeable by www-data.
You could just chmod 777 /tmp/log.txt, but that would mean everyone who has access to your server can write to that log. Additionally, you may not want to always write to the same log when you're testing as when you're navigating through the web interface (Personally, I would find it confusing and cluttering).
PHPUnit and other unit testing services allow you to mock various objects. The problem is that you have classes calling Utils directly.
You have to find a way to manually override the constructor. Look at PHPUnit's manual to find out why this maybe isn't ideal.
So if you're not using Dependency Injection, what do you do?
PHPUnit suggests, amongst other fixes, moving this Utils object instantiation to another method and then stubbing/mocking that method in your unit test (I want to emphasize that this is after recommending Dependency Injection).
So the next best?
public function __construct()
{
$this->init();
}
private function init()
{
$this->utils = new Utils;
}
Now when you unit test, you can create a fake init method and it will be called as soon as the class is created.
In conclusion, the way you are currently instantiating classes is not scalable or easily testable in many real world situations. While it may be all right in limited situations, it is better to get used to the DI (Dependency Injection) pattern, because it will save you lots of headaches in the future.
I need to create approx. 5-7 classes, every class will contain a lot of members (let us say each class will contain 20 members). I could create them using public access, like:
class A {
public $myPropertyOne = '';
public $myPropertyTwo = '';
...
}
My preferred way of course to make these members private and create get/set methods for each property. I.e.
class A {
private $myPropertyOne = '';
private $myPropertyTwo = '';
public function getMyPropertyOne() {
return $this->myPropertyOne;
}
public function setMyPropertyOne($myPropertyOne) {
$this->myPropertyOne = $myPropertyOne;
}
public function getMyPropertyTwo() {
return $this->myPropertyTwo;
}
public function setMyPropertyTwo($myPropertyTwo) {
$this->myPropertyTwo = $myPropertyTwo;
}
}
But considering a class will have 20 properties, I will have in addition to this add 40 methods. And my concern here is how will this slow down the script and much more memory this will require (remember I am going to have several classes like this).
Another solution could be to use magic functions __set, __get but I don't want to, because the code completion in development IDE will not suggest properties which is crucial for me.
If this would be a compiled language (like C++) I would not have a question and would use the solution with getters, setters but since the PHP is interpreted language I am interested in my scripts to use less RAM and be as fast as possible.
Thanks in advance, any thoughts regarding this question would be much appreciated!
My Opinion
Thank you all for your answers, I just wanted to share my opinion in case someone will look for an answer to this question.
I cannot fully agree with those who say that you should not care about performance as this is task of optimizers, I think this is important factor (well atleast as for me), when we're dealing with interpreted language such as PHP we will always have to think about memory and speed (this all reminds me the time when I was developing system apps for DOS, heh :) and you always have been limited with poor CPU and kilobytes of total RAM so you got happy if you could save an additional byte), in PHP development you have the same picture as regardless of how many server you add, users' count will be always higher so that you always have to decide if you want to follow classic/safe/proper method or to avoid this and get some gain in speed or memory.
So.... my opinion is that the best way here is to use public access for all member and avoid getters/setters for all properties and use private access with get/set methods for properties which requires data validation or initialization before a value will be set.
For example:
class B {
public $myPropertyOne = '';
public $myPropertyTwo = '';
private $myPropertyThree = array();
public function getMyPropertyThree() {
return $this->myPropertyThree;
}
public function setMyPropertyThree($val) {
if(!is_array($val)) {
return;
}
$this->myPropertyThree = $val;
}
}
Thank you for spending time on my question!
Simple test shows instances take the same amount of memory, unaffected by the number of methods in a class:
Class with no methods:
class Test1 { }
Class with 20 methods:
class Test2 {
function test1() { return true; }
function test2() { return true; }
function test3() { return true; }
function test4() { return true; }
function test5() { return true; }
function test6() { return true; }
function test7() { return true; }
function test8() { return true; }
function test9() { return true; }
function test10() { return true; }
function test11() { return true; }
function test12() { return true; }
function test13() { return true; }
function test14() { return true; }
function test15() { return true; }
function test16() { return true; }
function test17() { return true; }
function test18() { return true; }
function test19() { return true; }
function test20() { return true; }
}
Test loop, same for both tests:
$test = array();
$base = memory_get_usage();
for ($i = 0; $i < 10000; $i++) {
$test[] = new ClassToBeTested();
}
$used = memory_get_usage() - $base;
print("used: $used\n");
Result for class Test1 (no methods):
used: 3157408
Result for class Test2 (20 methods):
used: 3157408
I've run it in two separate scripts, since running the two tests in a single script apparently exposed some PHP internal allocation, and the second test consumed less memory than the first, no matter which one is first or second.
While you surely take more memory for the actual class definition, apparently this cost is incurred only once per class, not per instance. You don't have to worry about the memory usage.
But considering a class will have 20 properties
Having this many properties is usually an indicator of misplaced information. Check whether you can group some of those into Classes of their own.
Refactoring: Extract Class
I will have in addition to this add 40 methods.
Not at all. Unless these classes are dumb data structs, you dont want any Getters and Setters on them because they break encapsulation. Put methods in the public API with which you tell the objects to do things.
Getter Eradicator
Getters and Setters are evil
Tell Don't Ask
And my concern here is how will this slow down the script and much more memory this will require (remember I am going to have several classes like this).
This is not an issue.
In PHP, are objects methods code duplicated or shared between instances?
Another solution could be to use magic functions __set, __get but I don't want to, because the code completion in development IDE will not suggest properties which is crucial for me.
Modern IDEs can autocomplete on magic methods.
Code Completion for private/protected member variables when using magic __get()
However, if you are already concerned about performance at the microlevel, then you dont want magic methods because those are definitely slower.
__get/__set/__call performance questions with PHP
Apart from that, Magic Methods are not substitutes for getters and setters but error handlers that get triggered when an inaccessible property or method was called.
PHP __get and __set magic methods
Also, magic methods are unobvious and make for hard to read APIs.
To make properties of your class that implemented by magic methods to be highlited by IDE just use #property PHPDoc #property tag, like this:
<?php
/**
* #property int id Blog post ID
* #property string title Blog post Title
*/
class Post {
}
More on PHPDoc' #property here: http://manual.phpdoc.org/HTMLSmartyConverter/PHP/phpDocumentor/tutorial_tags.property.pkg.html
As for other issues questioned - Karoly Horvath' comment fully covers those PHP OOP a lot of setters, getters.
As stated before, it's quite strange that your class should have so many properties. However, it can sometimes (fairly rarely though) happen. But normally, those properties should have a sort of link together : so you could store them in a hashmap and not a property. Then you just neeed one method as a getter.
Now, it will surely be more resources consuming, true. As for autocompletion, use constants : you'll just type something like :
$my_class->getFromHashMap($parameter)
And when typing your parameter, you'll use the constant as it's stored in the class : here, the autocomplete should be able to help you.
Take in mind that my code considered that properties' name have been declared in lowercase...
<?php
class Modelo {
var $attr1 = "default";
var $attr2 = 0;
public function __call($name, $arguments)
{
if (method_exists($this, ($method = $name))){
return $this->$method();
}
else{
$attribute = split("get",$name);
if(count($attribute)==2){
$attribute = strtolower($attribute[1]);
if(isset($this->$attribute)){
return ($this->$attribute);
}
}else{
$attribute = split("set",$name);
if(count($attribute)==2){
$attribute = strtolower($attribute[1]);
if(isset($this->$attribute) && count($arguments)==1){
$this->$attribute=$arguments[0];
}else{
die("$name number of arguments error: ".join($arguments,","));
}
}else{
die("$name doesn't exist!");
}
}
}
}
}
echo "<pre>";
$m = new Modelo();
print_r(
array(
"objetct"=>$m
,"getAttr1"=>$m->getAttr1()
,"getAttr2"=>$m->getAttr2()
)
);
echo "setAttr1\n";
$m->setAttr1("by set method");
print_r(
array(
"objetct"=>$m
,"getAttr1"=>$m->getAttr1()
,"getAttr2"=>$m->getAttr2()
)
);
?>
You could try this:
trait get_set
{
public function set($what, $value)
{
$this->{$what} = $value;
}
public function get($what)
{
return $this->{$what};
}
}
It will work on public and protected variables. You can add if(!isset($this->{$what})error()
I'm used to java, objective c and a little c++.
Now i want to use PHP to create a website. I created several classes but to keep it simple: 3 classes.
Account - DataMapper - DataManager
This means that i can get an account from the database. In DataManager i keep track of all things. Like the userId of the user.
The thing is, normally all setted variables stay 'set', but now i'm using php i apperently need to store them by using a session.
DataManager:
<? php
class DataManager
{
// Hold an instance of the class
private static $dm;
private $dataMapper;
private $dictationView;
private $userId;
private function __construct()
{
$this->dataMapper = new DataMapper();
$this->dictationView = new DictationView();
}
// The singleton method
public static function singleton()
{
if (!isset(self::$dm)) {
$c = __CLASS__;
self::$dm = new $c;
}
return self::$dm;
}
// Prevent users to clone the instance
public function __clone()
{
trigger_error('Clone is not allowed.', E_USER_ERROR);
}
function __get($prop) {
return $this->$prop;
}
function __set($prop, $val) {
$this->$prop = $val;
}
}
?>
If i set the userId in the singleton DataManager class, the next time i
call an instance of the DataManager class it will not rememeber the userId. Somewhere i have to deal with session i guess. How to use sessions in a good OOP way in the DataManager? Thanks!
If you want you can create a wrapper for sessions in PHP. It actually could be beneficial, especially if your application later had to migrate to a cluster of servers and sessions would be moved to a distributed cache. Then, to facilitate this migration you would only have to provide different implementation if same Session class interface.
That said.
This code there itself is not a good OOP. You should stop using singletons. And, if you class require instances of DataMapper and DictationView, then they should be created outside the class and provided in the constructor. Instead of creating a tight coupling because you constructor is making other objects.
Now, what you refer to is not PHP but rather how a client-server architecture is being handled.
Here is a change, which assumes you manage the session correctly (with regard to session_start - should be in the bootstrap of your file)
I have also added some of topic corrections to your code, which will help u in the future:
private function __construct()
{
$this->dataMapper = new DataMapper();
$this->dictationView = new DictationView();
}
// The singleton method
public static function singleton()
{
if(isset($_SESSION[self::MY_UNIQUE_IDENTIFIER] &&
get_class($_SESSION[self::MY_UNIQUE_IDENTIFIER] == 'DataManager'){
self::$dm = $_SESSION[self::MY_UNIQUE_IDENTIFIER];
}
if (!self::$dm) {//LOOK HERE LOOK HERE!!!!!!!!!!!!!!!!!!!!
$_SESSION[self::MY_UNIQUE_IDENTIFIER] = self::$dm = new self;
}
return self::$dm;
}
// Prevent users to clone the instance
public function __clone()
{
trigger_error('Clone is not allowed.', E_USER_ERROR);
}
function __get($prop) {
return $this->$prop;
}
function __set($prop, $val) {
$this->$prop = $val;
}
}
//LOOK HERE LOOK HERE no closing ?>
Some traps I did not address here as they are not the subject of this question:
The right way to manage sessions
Adjustment to the class to allow inheritance without trashing the session
For the sake of simplicity, assume I have 2 classes, User and UserStatus, used in a Web application.
<?php
// library code:
class UserStatus {
protected $_status = NULL;
private function fetchDataFromDB() {
// regular DB stuff
$this->_status = ...
// result will be something like 'online', 'away', etc.
}
public function getIcon() {
global $icon_array;
if (is_null($this->_status)) {
$this->fetchDataFromDB()
}
return $icon_array[$this->_status];
}
}
class User {
protected $user_id;
public $user_name;
protected $status;
public function __construct() {}
public static function getAll() {
// some DB stuff
return $users;
}
}
// and now, in index.php:
$users = User::getAll();
// echoes the icon to use to reflect the current user status
foreach ($users as $user) {
echo <img src="$user->status->getIcon()"/>;
}
?>
In most of the HTTP request the status object will not be used so I'm looking for a way to only instantiate it as needed (call it lazy loading). How should I intercept the status->method() call and create that object on-the-fly?
An important note is that I need $user_id available in the UserStatus class, otherwise the fetchDataFromDB() method won't know to which user it should fetch the data. How should this be done?
I've looked at some interesting stuff on this matter like Fabien Potencier's What is Dependency Injection? and Pimple - a PHP 5.3 dependency injection container and also some articles about the Proxy Pattern but to implement them it looks like I have to mess a lot with the current code. Is there a simpler way?
Maybe im missing something but it seems the easiest solution in this instance would be to have your getter for Status simply create the object if it doesnt exist...
public function getStatus()
{
if(!isset($this->status))
{
// or however you creat this object..
$this->status = new UserStatus($this->user_id);
}
return $this->status;
}
public function __get($property)
{
$method = 'get'.ucfirst($property); // getStatus
if(method_exists($this, $method))
{
return $this->$method();
}
}
By using the __get magic method anytime you do $user->status it will call $user->getStatus(). Ofcourse you could also always just access it like: $user->getStatus()->getIcon() as well.
However you decide to set up accessing your properties i would recommend doing it in a consistent way across your entire model.
You could put the status class in a different file and then leverage php's autoloading mechnism:
http://php.net/manual/de/language.oop5.autoload.php
to not load that file until you access it.
There are rumors that auto loading (or actually just any kind of conditional loading) is troublesome for byte code caches and optimizers though unfortunately I don't know too much about the impact.
P.S.: The manual does not say rhis explicity at this point: You can also use spl_autoload_register() instead of just defining the magic __autoload function. This is slightly more powerful.
Im thinking of making a custom datatypes / prototypes for a project im working on but im wondering if its such a good idea?
For example
class String
{
var $Value;
private $escaped = false;
function __construct($String)
{
$this->Value = $String;
}
function escape()
{
if($escaped === false)
{
$this->Value = Registry::get('Database')->escape($this->Value);
}
return $this;
}
function trim()
{
$this->Value = trim($this->Value);
return $this;
}
function __toString()
{
return $this->__toString();
}
}
$myValue = new String('Hello World')->trim()->escape();
//$myValue is now prepared for DB insert
There will be prototypes for Array, Object, String, Resource etc..
with arrays there will implement Iterator and such
Some benefits i have in mind is specific data types to objects for example
interface Insert
{
public function Insert(String $Value); //Array / Object / Resource
}
The custom prototypes would be useful for all strings.
But do you think that the amount of resource usage will out way the benefits ?
updated for POC
$String = new String('ValueText');
sprintf('Test %s',$String); //Works
trim($String); //Works
base64_encode($String); //Works
Also for arrays the SPL Library would be perfect.
class Array implements ArrayAccess, Iterator, Countable
{
public function __construct(){}
public function offsetSet($offset,$value){}
public function offsetExists($offset){}
public function offsetUnset($offset){}
public function offsetGet($offset){}
public function rewind(){}
public function current(){}
public function key(){}
public function next(){}
public function valid(){}
public function count(){}
}
Another idea would be the extendible entities
class DatabaseVariable extends String
{
function __construct($string)
{
parent::__constrcut($string);
}
public function escape()
{
//Blah
}
}
Having a new entity extend a data-type will make it inherit available methods for that data-type.
As discussed about autoboxing, this is the exact system im looking for but as its not passed discussions yet, for my new project (Forum System) witch I started the other day, do you think that I should go ahead and use my idea?, the user will be able to do faster interactions with datatypes, and if there is a function that does not support an object being passed, we can also do
$RawResource = $Resourtce->Raw();
//...
$Resource->Set($RawResource);
In my opinion, the time you spend writing this code, fixing this code, and cursing the fact that you can't use hundreds of PHP functions with your classes will outweigh any advantage this code may have.
Also, the developer who inherits your project will hate you.
Sounds like way too much trouble for... seemingly no benefit.
If you're worried about forgetting to escape stuff, stop escaping things altogether and start using parametrized queries.