ken
ken

Reputation: 9013

Pinning objects to memory

I'm trying to think of a simple way to permanently pin a PHP object to memory and then have it available to other more transient objects to message with during their normal job of servicing page requests. I'm still relatively new to Wordpress so maybe I'm making things too complicated ... let me demonstrate through an example what I would want to be able to do:

  1. Have a UOM (unit of measure) object load up at startup that polls the database for a list of units, the default units, categories of units (e.g., pounds is an imperial measurement), conversion rates, etc.
  2. Subsequent service requests that want to use UOM conversions or lookups would simply call the global UOM object ( $UOM->get_measures_for_category ('speed') ). This object would already be in memory and not need to go back to the database to service requests.
  3. An update() method on UOM would allow event or timing based triggers to ask for the UOM object to update itself.

This is just one example of where there is a some relatively static set of data that is used regularly by service requests and the repeated querying of the database would be wasteful. Hopefully people are familiar with this pattern and could maybe point me to some examples of how you would do this in a Wordpress/PHP environment.

Upvotes: 1

Views: 114

Answers (2)

ken
ken

Reputation: 9013

I did not make my question clear when I initially posted but based on the conversation with Tom, I have agreed to repost this more clearly on Stack Overflow.

Upvotes: 0

Tom J Nowell
Tom J Nowell

Reputation: 9981

For what you want this is not the best way of doing it. However what you're talking about requires knowledge of one of the fundamental tennets of PHP and programming in general aka scope, namely what the global scope is.

So, if you declare this in the global scope:

 $uom = new UOM_Class();

Then in any file afterwards you write:

global $uom;
$uom->something();

it will work.

This is all wasteful however, instead you would be better with static methods, and something more like a singleton pattern e.g.:

UOM::Something();

I leave it as a task for you to learn what a singleton is, and what scope is, these are fundamental tennets of PHP, and you should not claim to know PHP without knowing about scope. The best way of putting it is when in everyday conversation, it is called context, the global scope is tantamount to shouting in everyones ear at the same time. Everyone can access it, and its not something you want to pollute

I'm sorry if I seem a bit harsh, here's some articles that should help, they talk about scope, singletons and some other methods of doing it, like object factories

http://php.net/manual/en/language.variables.scope.php http://www.homeandlearn.co.uk/php/php8p2.html

http://php.net/manual/en/language.oop5.patterns.php

Upvotes: 3

Related Questions