Object persistence in php

object persistence in php

Usually you get your persistence by using the database. If that’s a bottleneck you start caching data, for example in memcached or maybe a local file with a serialized array on your webserver.

Read More

Stop using singleton and use dependency injection.

Best way is to use DataMapper (http://www.martinfowler.com/eaaCatalog/dataMapper.html) and attach it to an object by means of dynamic properties. Let the data mapper handle persistence.

$CS = new CookieStorage(); $SS = new SessionStorage(); $FS = new FileStorage('config/object.db'); $DM = new ObjectDataMapper($FS); $O = new Object($DM); $Object->DynamicProperty = 1; 

Now DynamicProperty will automatically persist and will automatically be loaded from file object.db . And the class definition:

class Object < public function __construct(MapperInstance $Storage = NULL) < $this->setMapper($Storage?: new ObjectDataMapper(new FileStorage('config/object.db'))); > public function __get($name) < $this->_Mapper->getProperty($name); > public function __isset($name) < $this->_Mapper->isProperty($name); > public function __set($name, $value) < $this->Mapper->setProperty($name, $value); > > 

Data persistence in Web programming is done thru the use of cookies/sessions and passing cookie/session variables across Web page calls. Theoretically, any kind of data can be stored in these variables — but for most practical purposes, only the more important data (look at them more like tokens) needed to identify/reconstruct the needed objects (with or without a database) are transferred to and from server and browser.

bcosca 17131

Similar Question and Answer

I’d advise you take a good look at memcached. When you’re talking server load and performance capabilities, a useful metric is often pages/second. If you have a dedicated server and unoptimized but very intensive stuff going on, you may only be able to serve 5 pages/second. Utilizing data caching is a great way to increase that 3 to 10 fold. However, it’s always a tradeoff as far as how stale the data can get. You will really need to test your site to properly understand (quantify) other possible performance-limiting factors such as other connections per page (images, css, etc), file i/o, other network activity, and last but not least the actual

Читайте также:  Codes in doing html

It is possible to store objects in the current session. Now just create a base class which is able to store and recreate the object itself. Any derived object will then also be persistent.

As far as i know the session is stored in RAM and thus should be faster than serialize the objects to disk to achieve persistence.

Though it may not be the prettiest solution, but you can use SESSIONS for this matter.

and on another page, you can call the object simply with:

$object = unserialize($_SESSION['object']); 

Though ofcourse this approach seems the easiest. It should come with utmost precaution:

  1. Know that sessions depending on the traffic of your server should not be too large in size as many users concurrently ask for each of these sessions. Scale the size at your own discretion.
  2. always serialize and unserialize as sessions not done so will misbehave.

What ever sails your boat. Do so at your own mindful analyzation. goodluck

PHP does not have the concept of persistence as Java does: the JVM allows for Java applications to persist in memory between HTTP requests; the webserver forks a new PHP process every time a new HTTP request is served so an object’s static variables will not persist data for you between requests.

Use a database to store persistent data. Web programming focuses on concurrency, so you shouldn’t worry about database queries — 20 a second is few. If you reach the limits of your database you have the options to add a caching layer or «scale out» hardware by adding read-only slaves.

More Answer

  • Convert array to object in php — Convert this array to object in php
  • How can I convert 2 PHP arrays into 1 JSON object array?
  • PHP magic method __toNumber() converting object to number
  • PHP — Group similar key in one Object
  • Prepend data in a key-value Object in php
  • How can i delete object from json file with PHP based on ID
  • How can I transform a jquery object into a php array?
  • Get property from php object
  • PHP problems with using static object
  • Most efficient way to check if object value exists in PHP 7
  • PHP — Accessing a object property from dynamic variable
  • PHP mysqli_query() expects parameter 1 to be mysqli, object given in
  • PHP get keys from array in object
  • How to process complex json object in PHP
  • Parsing JSON object in PHP using json_decode function
  • How to get object name in PHP
  • PHP server unable to receive javascript object using ajax
  • How to merge two arrays of object without duplicates(using the object id) in PHP
  • PHP access object member as if array member
  • Nested method in php object
  • PHP object _construct function
  • Why does assigning a new object to a PHP array value cause a ParseError?
  • AJAX Post to PHP with JSON Object containing a File
  • php variable in a javascript object within a json result
  • Displaying Arrays in PHP using Object Oriented Programming
  • Object error when trying to print index 0 on array with PHP
  • use muliple method in one object in php
  • Add interval to DateTime object prior to PHP 5.3
  • Creating object in PHP of predefined class type
  • how to remove an object reference from a php array without destroying its object
  • PHP implode() using conditional logic based on object index
  • PHP ReflectionClass — Fatal error: Class name must be a valid object or a string
  • Getting information out of a PHP object
  • where does php output go if json object not returned
  • Search value in array object in PHP
  • PHP OOP design: an object can have several ‘modes’. How do I define them?

More answer with same ag

  • How to replce ony array value with other array value in a specific index?
  • php parse the string obtained inside the XML tag
  • How to get a file updated server side at given times
  • What’s the difference between «string» .$var and «string $var» in php?
  • Any library to handle incoming email and parse it?
  • PHP Getting Key from object where key is integer
  • Converting an ASP function to PHP
  • replacing «manual file upload» with fetching files from «defined directory»
  • passing a variable by value using php
  • PHP Sum integers in an array
  • using preg_match_all image source with user defined tags
  • Creating default object from empty value ( stdClass? )
  • How to convert a string into condition in the IF statement
  • Slim Framework — how to output arrays without templates?
  • Combine two array using a field in PHP
  • htaccess cannot load correct content
  • Setting the result of an if statement
  • Same SQL in Oracle console works and in php not
  • Error create cakephp model named «Models»
  • Posting on facebook fanpage as page via app [access token issue]
  • Confused about date-time difference in months and years
  • Checkboxes do not get checked
  • Symfony 4 — PHP convert multidimensional array to javascript
  • How to create Openid, Google, Yahoo, facebook, twitter without using Gigya.com in php?
  • How to extract character and number from alphanumeric value using php
  • Remove an element from an explode() array
  • How to disable xdebug during laravel installation via composer
  • PHP: Iterating Through a multidimensional Array (4D)
  • Disable option that already selected by another select (add select box dynamically)
  • Trying to remove subdomain by php explode
  • Best way to scrolldown onpageload
  • jax-ws, authentication for php clients
  • update markers on google maps using php and ajax
  • Should searching be done in the view?
  • Twilio PHP Lookup API is returning no response if number is not correct?
  • How Can I get a full result from a sql query using php and then display that with javascript
  • Change image resolution using imagick
  • Automated jobs with failover written in PHP
  • Declare an object as a specific class in php
  • Is there any better way to loop through 2d array row wise in php
  • greek letters validation php string
  • Block direct HTTP access to a PHP File
  • Regex to convert Email to Name
  • How to subtract a html textbox from a PHP variable?
  • readdir() includes an empty folder
  • How to get everything between brackets but only those, which are not wrapped into brackets themselves
  • How to run multiple PHP scripts from CLI
  • TYPO3 extbase how to end a script properly
  • PHP undefined method DOMNodeList::setAttribute()
  • best way to store a variable available to every session in php

Источник

object persistence in php

Usually you get your persistence by using the database. If that’s a bottleneck you start caching data, for example in memcached or maybe a local file with a serialized array on your webserver.

Solution 2

PHP does not have the concept of persistence as Java does: the JVM allows for Java applications to persist in memory between HTTP requests; the webserver forks a new PHP process every time a new HTTP request is served so an object’s static variables will not persist data for you between requests.

Use a database to store persistent data. Web programming focuses on concurrency, so you shouldn’t worry about database queries — 20 a second is few. If you reach the limits of your database you have the options to add a caching layer or «scale out» hardware by adding read-only slaves.

Solution 3

Though it may not be the prettiest solution, but you can use SESSIONS for this matter.

and on another page, you can call the object simply with:

$object = unserialize($_SESSION['object']); 

Though ofcourse this approach seems the easiest. It should come with utmost precaution:

  1. Know that sessions depending on the traffic of your server should not be too large in size as many users concurrently ask for each of these sessions. Scale the size at your own discretion.
  2. always serialize and unserialize as sessions not done so will misbehave.

What ever sails your boat. Do so at your own mindful analyzation. goodluck

mattgoody

Comments

I am fairly new to web programming, I have mainly used java to create desktop applications in the past. I’m trying to figure out how to create persistent objects in php. Maybe persistent isn’t the right word, I don’t want the object to be unique to each client, like i would get by serializing it in a session variable. I want the object to be created on the server and have that same object be accessible at all times. The object would query the database and store some data. This way, each page load, the php code would get that data from the same persistent object rather than having to query the database each time. I am currently using the singleton pattern for object creation because my initial understanding was that it would allow me to accomplish what i want. Part of the object is an array, and when i execute a php page that adds a value to the array, and access that value on the same page, its fine. However when i add a value to the array and then load another page that accesses the value, the array is back to being empty. Is this possible? Am i overreacting in thinking that querying the database so much is bad? There will at times be as many as 20 users requesting data during any one second, and i feel like thats ridiculous to query the db each time. Thanks

p.s memcahced supports multiple servers, and is a very well tested and stable extension. apc is great on one server, and supports custom use, but memcached still wins when you talk about a distributed app. However, you’ll have to do some interesting work with increment as a «lock» logic, because another page could have modified the value by then. depending on memcached will work fine, but take care when coding this interface so you don’t assume it hasn’t changed and overwrite newer data. php.net/manual/en/memcache.increment.php

Keyne Viana

For simple queries, which is faster, query over and over the database for the same data, o cache the object? Let’s say that the query itself takes 0.1 secs. Usually, which is faster file+serialized-object or database+object-population?

Tarion

Bart Burg

You should always care about performance. It could spare a bunch of time learning it correct right away. I’ve had to adjust a project made by someone else once, which was made in PHP and had performance issues. It took me a very long time to solve. Longer than he would have doing it right right away.

@KeyneON Databases use files. some databases are separate from the server they are on. so technically direct file access will always be faster. databases will always be more convenient.

Источник

Оцените статью