PHP - static classes and caching classes

2019-04-12 05:33发布

问题:

The code below is how I used to cache objects in Java.

class Account{
    private static ArrayList<Account> accounts = new ArrayList<Account>(); //Array that holds Account objects
    private String username; //Unique Name or Username

    public Account(String username) { // constructor
        this.username = username;
        Account.accounts.add(this); //Add object to accounts Array
    }

    public String getUsername() { 
        return this.username; // Return username
    }

    public Account getAccount(String username) { //Get object "Account" with username
        for (Account acc: Account.accounts) { //Foreach loop that loop over all accounts from the Array
            if (acc.getUsername() == username) return acc; // Return Account object if given username == object's username
        }
        return null;
    }
}

I commented it so it will make sense if you don't understand Java but Java OOP is similar to PHP OOP.

From the Java code above I can hold all objects on an Array, So it doesn't query the Database all the time.

1) I'm wondering if I can do something similar with PHP to speed up code and cache classes. If this is possible can you please show me an example. If not what would be the best way to achieve this?

2) What are some good practices to use when object oriented programming to keep memory usage low?

Thanks in advance

回答1:

The biggest difference between a Java app and a PHP app is that Java is typically a constantly running program handling several incoming connections at once, while PHP instances are started and torn down by the hosting web server for every single individual request. That means any class you load or object you instantiate or variable you assign only has a lifetime of a number of milliseconds (in a decently fast application). Static class properties work the same as in Java, however, the entire application is torn down after a few milliseconds, so this doesn't work as a long-term cache. And more importantly, each individual HTTP request is its own independent thread, so assigning something in one thread doesn't make it visible in any other simultaneous or subsequent threads.

To cache something cross-request, you need an external data store. For this you have many options, depending on what suites you best:

  • serialize to a file
  • APC
  • memcached
  • Redis
  • sessions (for per-user data storage)
  • many more


标签: php oop caching