Lazy loading in PHP

In more pro­jec­ts than I care to think about, I’ve seen a pat­tern that I dis­li­ke the more I see it. It appears qui­te inno­cent, but it brings about cost with no dis­cer­ni­ble bene­fit.

Inclu­ding all of the application’s source code on each and every call being made to a page. It may be that one file is inclu­ded that lists all files the app brings along; it may be a list of require_once state­ments in every ent­ry page it has. But what is the bene­fit? Even if the page loads only tho­se files that it might even­tual­ly need, it pro­bab­ly inclu­des more than is war­ran­ted given the task it is cur­r­ent­ly given.

One solu­ti­on is to get into using an auto­loa­der; let the inter­pre­ter figu­re out by its­elf whe­ther it has alrea­dy seen all that it needs to exe­cu­te a given pie­ce of code. The other opti­on is to requi­re exter­nal files only at the point that you’re cer­tain that you need them. Does your code do input saniti­zing and vali­da­ti­on befo­re it loads the clas­ses that then work with the saniti­zed values? Pro­bab­ly not – it’s much more com­mon to first load all the code, and only then start to work with what you are given.

Lazy loa­ding means that the inter­pre­ter only runs on tho­se code parts it needs, hel­ping to con­tri­bu­te to bet­ter app­li­ca­ti­on per­for­mance (becau­se we’re not spen­ding time on code we don’t real­ly need, any­way). This also means using less resour­ces on the ser­ver, which means bet­ter use of resour­ces – ulti­mate­ly, having your code use less elec­tric power. But the­re is even more bene­fits: code that has not been loa­ded can­not be causing any kind of inter­fe­rence; you’re cer­tain that you don’t have to look into tho­se files when you’re debug­ging. And then, code that has not been loa­ded also can­not be used for secu­ri­ty exploits – so you have less side effec­ts the­re as well.

It’s not that this is a par­ti­cu­lar­ly com­plex intel­lec­tu­al chal­len­ge, it’s more a mat­ter of per­spec­tive and may­be wri­ting infra­st­ruc­tu­re code for your app. But to me, the bene­fits are worth the few more minu­tes spent whilst thin­king about your code.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.