General stuff

Php5 Singleton pattern with magic __get and __set

March 30th, 2008 at 11:41am Under General stuff+ Php+ Php 5

I wanted to reproduce a simple singleton design pattern in PHP 5. After reviewing many overly complex examples, I synthesized to this example.

It also makes use of the PHP5 magic function __get and __set also poorly addressed in web postings. Going for cleaner code I like to see $obj->prop rather than $obj->getProp() and $obj->setProp(value) in the code. But I am greedy and want to have read only and write only props. So I configured the various examples to achieve that goal. As well you can see in the __set and __get methods you may choose to work the props or call a private method that would handle the validation and proper handling of the set and return values. I demonstrated this here.

This is the singleton running with the idea of a single configuration object for an application. It only has one real property named isDebugging for the example.

  1. <?php
  2.  
  3. class Config {
  4.    static private $_instance;
  5.     private $isDebugging = false; // Read write
  6.    private $version = "1.1"   ;  // Read only
  7.    private $cannotReadProp = "x" ;
  8.    public static function getInstance($args = array())
  9.    {
  10.       if(!self::$_instance)
  11.       {
  12.          self::$_instance = new Config();
  13.          
  14.       }
  15.       self::$_instance->setIsDebugging(isset($args['isDebugging']) ? $args['isDebugging'] : self::$_instance->isDebugging);
  16.       return self::$_instance;
  17.    }
  18.  
  19.    private static function setIsDebugging($value)
  20.    {
  21.       self::$_instance->isDebugging = is_bool($value)? $value: self::$_instance->isDebugging;
  22.    
  23.    }
  24.    
  25.    public static function __set($prop, $value)
  26.    {
  27.       if (isset(self::$_instance->$prop))
  28.       {
  29.          switch ($prop)
  30.          {
  31.             case 'isDebugging':
  32.                self::$_instance->setIsDebugging($value);
  33.                break;
  34.  
  35.             default :
  36.                throw new Exception('Cannot write property [' . $prop . ']',1);
  37.          }
  38.  
  39.       }
  40.       else
  41.       {
  42.          throw new Exception('Undefined property [' . $prop . ']',1);
  43.       }
  44.    }
  45.    
  46.    public static function __get($prop)
  47.    {
  48.  
  49.       if (isset(self::$_instance->$prop))
  50.       {
  51.          switch ($prop)
  52.          {
  53.             case 'isDebugging':
  54.                return self::$_instance->isDebugging;
  55.                break;
  56.             
  57.             default :
  58.                throw new Exception('Cannot read property [' . $prop . ']',1);
  59.          }
  60.  
  61.       }
  62.       else
  63.       {
  64.          throw new Exception('Undefined property [' . $prop . ']',1);
  65.       }
  66.    } 
  67.  
  68.  
  69. }
  70. ?>

This is a testing script for the above. Note there are some commented lines for testing the exception thowing.

  1. <?php
  2.    include 'config.inc.php';
  3.    
  4.    // First reference
  5.    $myConfig1 = Config::getInstance();
  6.    
  7.    // Get property
  8.    echo ('$myConfig1->isDebugging:' . ($myConfig1->isDebugging ? "true" : "false")) . '<br/>';
  9.    // Set property
  10.    echo 'Set $myConfig1->isDebugging = true <br/>';
  11.    $myConfig1->isDebugging = true;
  12.    echo ('$myConfig1->isDebugging:' . ($myConfig1->isDebugging ? "true" : "false")) . '<br/>';
  13.    
  14.    // Second reference
  15.    echo '<br/>';
  16.    echo 'Add second reference and not getInstance args<br/>';
  17.    echo '$myConfig2 = Config::getInstance(); <br/>';
  18.    $myConfig2 = Config::getInstance();
  19.    
  20.    echo ('$myConfig1->isDebugging:' . ($myConfig1->isDebugging ? "true" : "false")) . '<br/>';
  21.    echo ('$myConfig2->isDebugging:' . ($myConfig2->isDebugging ? "true" : "false")) . '<br/>';
  22.    
  23.    // Third reference
  24.    echo '<br/>';
  25.    echo 'Add third reference and change prop via getInstance arg <br/>';
  26.    echo '$myConfig3 = Config::getInstance(array(\'isDebugging\'=>false)); <br/>';
  27.    $myConfig3 = Config::getInstance(array('isDebugging'=>false));
  28.    echo ('$myConfig1->isDebugging:' . ($myConfig1->isDebugging ? "true" : "false")) . '<br/>';
  29.    echo ('$myConfig2->isDebugging:' . ($myConfig2->isDebugging ? "true" : "false")) . '<br/>';
  30.    echo ('$myConfig3->isDebugging:' . ($myConfig3->isDebugging ? "true" : "false")) . '<br/>';
  31.    
  32.    // Set property via second instance
  33.    echo '<br/>';
  34.    echo 'Set property via second instance <br/>';
  35.    echo 'Set $myConfig2->isDebugging = true <br/>';
  36.    $myConfig2->isDebugging = true;
  37.    echo ('$myConfig1->isDebugging:' . ($myConfig1->isDebugging ? "true" : "false")) . '<br/>';
  38.    echo ('$myConfig2->isDebugging:' . ($myConfig2->isDebugging ? "true" : "false")) . '<br/>';
  39.    echo ('$myConfig3->isDebugging:' . ($myConfig3->isDebugging ? "true" : "false")) . '<br/>';
  40.    
  41.    
  42.    
  43.    // Set property to incorrect data type
  44.    echo '<br/>';
  45.    echo 'Set $myConfig1->isDebugging = 123<br/>';
  46.    echo 'No exception for invalid data type and not prop change.<br/>';
  47.    $myConfig1->isDebugging = 123;
  48.    echo ('$myConfig1->isDebugging:' . ($myConfig1->isDebugging ? "true" : "false")) . '<br/>';
  49.    echo ('$myConfig2->isDebugging:' . ($myConfig2->isDebugging ? "true" : "false")) . '<br/>';
  50.    echo ('$myConfig3->isDebugging:' . ($myConfig3->isDebugging ? "true" : "false")) . '<br/>';
  51.  
  52.    // Setter throws undefined property exception
  53.    //$myConfig1->test = true;
  54.    // Getter throws undefined property exception
  55.    //echo '$myConfig1->test:' . $myConfig1->test . '<br/>';
  56.    // Setter throws cannot write property exception
  57.    //$myConfig1->version = '2.2';
  58.    // Setter throws cannot read property exception
  59.    //echo '$myConfig1->cannotReadProp:' . $myConfig1->cannotReadProp . '<br/>';
  60.    
  61. ?>

By Lon Hosford Add comment

Flex LocalConnection Error #2044: Unhandled StatusEvent:. level=error, code=

March 13th, 2008 at 10:50pm Under Flash+ General stuff+ Flex

I have seen this error when trying to use SWFLoader and LocalConnection with a Flash SWF. The problem is related to using the LocalConnection but the Flash SWF has not played the requisite frame where its side of LocalConnection code appears. As such there is no local connection.

To see sample code to overcome this look at my post on using Flex, SWFLoader and LocalConnection: Flex LiveConnection and Legacy Flash SWFs

By Lon Hosford Add comment

Previous Posts


Recent Blog Posts

Categories

Blogroll

sport pharmacy anabolic steroidsbuy tramadol no rxintermediate for atorvastatin synthesispatient assistance program for wellbutrinlisinopril informationgreen tea clear marijuanalozenges viagraambien detection in urine screeneating marijuana seedsreduce estradioltadafil cialis on-line pharmaciespositive effects effexorbuy prescription ambien halcioncipro stoney creekmarijuana camoflauged trucks tuscontaking omeprazole still feeling sickorthos remingtonmedicare medicaid viagra artoil based injectable steroids listnaproxen interaction with ibuprofenpharmacy viagra priceloratadine steroidmetformin pricerx generic flomaxmarijuana nakeddilantin and glucosecetirizine hydrochloride doselipitor long term effectsviagra pulmonary hypertensioncheapest generic drug for remeronheroin's effect on unborn childrendextroamphetamine vs amphetaminepaxil gad message boardsheroin is so passe lyricsmarijuana and other drugssofttabs free doctor consultationwhat are fluconazole tablesnicotine patches dreamsarmour versus synthroidactonel otosclerosisnorco online consultationpregnancy ambienweihrauch 100 pcpcheapest diet phentermine pillritalin unfounded suspicionspizza hut san francisco somalow dose naltrexone for multiple sclerosissoma cruz castlevaniabuy clomid on lineoxycodone picture pillsinus infection acyclovirtylenol based pain reliefnicotine bottleoxycontin and other opiates helpfemale panel testosterone totaldental use and valiumhydocodone amitriptyline cymbalta lyrica back paindepakote spr512 mg oxycontindrug effects lisinopril sidemedical marijuana santa cruzrx ritalin get immediately phoenix azvalium drug testsdrug dealer price marijuanatrain wreck marijuanainderal interaction xanaxmarijuana for medical purposes in americadur dur d tre billycombining byetta glucophage and avandiafamous people that used steroidsnicotine and chronic paindirections for taking zithromaxiv xanax dosebuy folic acid 10mgis ambien okdrospirenone risperdalparoxetine from indialack of folic acid symptonscoumadin nri blood ratiodiscount adderalldidrex in mexicoxanax barbituratesfda actos warningsambien and weight gainca medical marijuana dispensary programmedrol and ruptured disksildenafil chemical nomenclaturepartition principale sur dique dur externemona morphineorder tadalafil pillhydrocodone allergic reactionsale propeciaadderall heart failuredrug insert viagraexpired ziacparoxetine introducedvagina marijuana pipescremascoli ortho12 b coumadin interactiondidrex weight loss pillsclonazepam chemical formulaclarithromycin in nexiummetoprolol adverse reactionsdrugs mailorder valiumwest virginia ortho photo browsertylenol pm drugnicotine patch 21 mg100mgs of zoloft works for meoverdose on heroincheap cardura at online pharmacyvicodin bother stomach curebenefit of ritalinin ky phentermineformater le disque durpaxil withdraw lawsuit lubbocksynthroid low dose symptomsultram lyrica seizuresfurosemide halucinations itching relatedpharmacology of viagraortho tri cyclen side effectsimprove effectiveness of morphinecervical cancer and clomideffects prednisone side sitephotos of poppies derived from heroinassessment nicotine dependencemarijuana archiveprednisone dogs cancerritalin fda approvalsingulair chewablesatorvastatin simvastatin equivalencyinositol ginkgo effexorpara methoxy amphetamine pmainformation re pepcidpharmacies viagraviagra for enhancementclonidine and withdrawaladvair long term side effectsbottle of tylenol liquidis marijuana annualnicotine is bad for youultram prescription drugcoupon levitraprilosec glutenvalaciclovir valtreximetrex imitrexdistrict of columbia marijuana legalscales to weigh marijuanaadd marijuanadoes viagra have an expiration datecheap viagra ukslipitor no prescriptionggt test and zocor1 mg dose iv morphineortho donjoyeighth ounce marijuanaselling marijuana around high schoolsprednisone acute coughyasmin abdallahbuy viagra cialistylenol 3 medicationortho tri lo side effectsheroin track markssuccess of pregency with clomidfluconazole food interactionbbs bbs php flomax lol tofeline ibd prednisonelipitor damageritalin and heart diseaseactive ingredients in pepcid completeavandia fda grahamavc im map plavixcan toprol make depression worselong term use of atenololphera-plex with testosterone stackpepcid package insertkenalog steroid injectionfree celecoxibhydrocodone apap 7.5 750 tbmck nursingmethylphenidate hcl tab 20mgortho evra clot riskchildren and nexiumranitidine and side and effectscost of viagra in the philippinesrandom dot orthomarijuana silhouettebuy propecia online dream pharmaceuticalin psoriasis ranitidineavandia pancreas cartoonfollicle size when taking clomidred dragon steroidsramipril migrainesortho mcneil3generic sildenafil viagraketamine v7czyban discountindiana marijuana task forcecheap generic viagra no prescriptioninformation zithromaxchildren's fever ibuprofen acetominophenmarijuana seedlingsoxycontin rashmicro retin reviewcyclobenzaprine hydrochloride 10mgeffects of lsd on societyhydrocodone abdominal painmarijuana supplementcirrosis liver ibuprofengeneric paroxetine hydrochloride 10mg pilllipitor nervousnesspurchase methylphenidate onlinebuy testosterone on line free shippingcelexa discountmarijuana yellow spots leaves drainageprilosec nexium samemarijuana legalization question in nevada5 mg dysfunction erectile sildenafilsolu medrol for spinal cord injuryaka gabapentin neurontinpass marijuana urine testecstasy green turtlesertraline prescription mexicodelayed period on clomidmarijuana vaporizortylenol 44325dangers of floventcelebrex compare vioxxclomid ovarian cancermorphine implant spinepcp socioeconomic classpenicillin mild tremors and weaknesspharmacies that sell phentermineopium aquariumoncology marijuanaortho meta para directorsclaritin side effectsnifedipine and bruisingmarijuana use effects headachesmedroxyprogesterone pregnancybuy tylenol with codeine without prescriptionprilosec and newsmarijuana tinctures cookingbooks about marijuanadesogestrel yasminmen taking viagramarijuana hating girlfriendsgetting of zoloft and busparweening off lexaproadvair on salegrow perfect marijuana plantszyban productssildenafil buy onlinecheap retin aheadache nortriptylinetriamterene 37.5 mgwhat people plants marijuana mostlyrabeprazole depressionoverdose of norvascdangers of snorting viagraclonazepam klonopin abuseactos and congestive heart failuremedical uses for viagrawhat is coumadin used fororange peels in marijuanaibuprofen use for dogs25 mg altacewomen testosterone hair lossorder generic ambienonline pharmacy levitravicodin 700mgprednisone withdrawal periodharvey sicherman orthoeffects of adderall on older adultsside effects diflucan searchhyperforin vs paxilpregnancy ritalinmetrogel perscription drugs metrogelnatural viagra free samplestramadol tablet photoclomid luteal phase lengthphentermine legal no prescriptionhydrochlorothiazide combination drugslamictal concomitant seroquelbt hydrocodone ibuprofen tbortho home defence maxhydrocodone no prescription requiredopium garden in miamibay carisoprodolpcp probesortho assisting school in denver coloradoambien cr vs ambienchewable valiumvyvanse vs adderall xrpics of haze marijuanaibuprofen totsealbuterol for infantson yasminhypoxic n oxide tamoxifennormal range for serum testosterone levelsflu medication tamifluwhat are zyprexa waffersheroin chic kate mossflonase and blood sugarmarijuana mcdonaldsphysical effects steroids havepharmacy xenical health insurance leadmethamphetamine recipes freenorco and buyvalporic acid levelaugmentin pravachol aciphex aciphex actos alessebuy fda no presciption adderallativan discreet from ukatarax doseageritalin alternativeswillie nelson marijuana arrestorder norvasc onlinebuy pharmacy phentermine xanaxchemical effects of marijuanagetting prednisone without a prescriptiontimothy o leary lsdcoupons for children s tylenoldrug reaction to cephalexin in dogsdrug interactions of losartanwellbutrin and panic disorderativan for flying fearfinding retin aname of generic lipitordrug interaction benadryl claritinlortabs takenegative affects of prozacindiana serzone attorneysgenetic tenuate bno prescriptionherbal female viagrabuy phentermine with discountfree samples imitrex injection 6mgcheapest phentermine around phentermine online cheepattorney oxycontin tennesseegeneric cialis 10mgketamine mechanism of actionlotrisone alternativevicodin recalldiscount hepsera hepsera hydrocodonedur o maticways to use marijuanamarijuana in francehydrocodone bitartrate and acetaminophen tablets medicalinstructions for smoking marijuanatransdermal testosterone replacement creamcheap phendimetrazine pillsheroin thrisha phothos10 claritinortho molecularmorphine standadgetting valium out of your systemrx prednisonemeridia education free legal formoxycodone perscription medicineultram b ultramdoctors who prescribe vicodinbest generic ultramabuse flomaxmarijuana and hair losscheap cost softtabs onlinemethamphetamine free base stabilitybest price for nexiumdiovan and patient commentsacetaminophen and dogfatal paroxetine overdosemetaformin and clomidherbal sibutraminemarijuana day afteinfant penicillin red rashecstasy 24 hourforum ipa allegra versace anorexiccellular growth and folic acidcost of paroxetinediscount bupropion smokingsibutramine orlistat without prior prescriptionbuy tetracyclineadderall alternative naturalpinnacle ortho georgialipitor heartviagra doctor freefluconazole evaluationfinasteride dosage while on steroid cyclenicotine in hand rolled cigarettesdisfunci n erectil metoprolol tartratoquarter pound of marijuanadetox drink for marijuanaadderall citric acidwin free marijuana seedscheap roche valium with overnight deliverycuellar cuellar in norco cacelexa toxicitycartia medicationpharmacy onlinepharmacy onlinepharmacy onlinepharmacy onlinemedical marijuana seedstoxicology tramadol lethal levelchemistry of bupropion and nicotine replacementwhat is opium drugzovirax while pregnantmorphine sulfate sq 5 1positive about steroidsentheogens marijuanamarijuana piecegeneric retin a 1isosorbide dinitrate structuredosage flomaxbuy cod delivery phentermine satfosamax versus evistadecrimilization of marijuanathe anxiety munity treatment medition busparsoma center highland park njexperiences on lsdnon nicotine chewing tobaccolsd and the truth about lifeharful substance in marijuanaritalin dandruffortho tri-cyclen nexiumsingulair problemecstasy colors and their meaningrochester heroin junkiescommview zybaneffects long side term use vicodincombining adderall and celexaweight gain with effexorclaritin ingredientranitidine and diphenhydramine2430 ritalinthanksgiving lexapro cold turkeyortho jonathan haas bipolarsildenafil citrate bulkgrowing marijuana 12clonidine drug interactionsortho evra help acnebuy adipex online without prescriptionrisperdal anxietypurple marijuana seeds for salecar leasing and pcpbuy tadalafil for less onlineoxycontin depression weak tired moodjulio franco steroidseffexor seroquelng ml hydrocodonepicture of a marijuana leafd nicotineneurontin for bad toothwhat is isosorbide dnwhen will i ovulate with clomidnioxin shampoo finasteridecoupons for prozacmethamphetamine free base sodium carbonatekirkland ibuprofenzyprexa short term memory losschest tight with loratadinefosamax mice thyroidpoems on teenagers doing marijuanagrapefruit juice and effexormorphine chronic pain libidozyrtec and pillcan dogs develop tumours from steroidssuicide and neurontin updatescostco pharmacy prices for aldaraover dose on the medication zoloftcephalexin dogs side effectscialis degenerci clomiddescription zyprexapregnancy and marijuanaoxycontin inventedativan prescription drugcambodian thai stick marijuanaimages of lsdestradiol 0.5mg and late periodsklonopin e615saliva testosterone testaffects of klonopin while pregnantcanadian flag w marijuana leafpicture of 10 mg diazepamwellbutrin prescribing informationsynthesized opiumortho tri cylen looxycodone indiacan oxycodone cause bad breathbupropion cheap online free shippingcvs pharmacy lexaproatenolol problemson lsddaniel jackson sick puke tylenol toilet5 sildenafil nasal congestionbuy viagra cialis levitra online prescriptionnasonex costbuy tadalafil from usa onlinetramadol chemical namegeneric meridia codmarijuana indoor cultivation humidityfluoxetine and alchoholyahoo health drug guide orlistat overview