{"id":5597,"date":"2022-02-21T04:31:47","date_gmt":"2022-02-21T04:31:47","guid":{"rendered":"https:\/\/studysection.com\/blog\/?p=5597"},"modified":"2022-02-21T06:33:40","modified_gmt":"2022-02-21T06:33:40","slug":"flyweight-pattern-in-php","status":"publish","type":"post","link":"https:\/\/studysection.com\/blog\/flyweight-pattern-in-php\/","title":{"rendered":"Flyweight Pattern in Php"},"content":{"rendered":"<p>The flyweight pattern is the structural pattern of today. Simply put, the Flyweight pattern is used to break down a large domain model into smaller domain models and a collection of smaller object-value classes called flyweights.<\/p>\n<p>Flyweight can be useful when you have a collection of objects that have repeating properties and you want to share these attributes, with the end goal being to save memory usage.<\/p>\n<h2>Useful note, before proceeding<\/h2>\n<p>Flyweight is extremely unusual in the <a href=\"https:\/\/studysection.com\/blog\/lazy-load-in-php\/\">PHP<\/a>  ecosystem, the benefits it provides are enormously useful in game development, as large amounts of objects are needed. Regardless, below I&#8217;m going to cover a game implementation you&#8217;re more likely to find in a language like Java or C++.<\/p>\n<h3>What is the flyweight pattern?<\/h3>\n<p>Flyweights are used to store the common and repetitive data required by the model. These values \u200b\u200bcan be stored in each individual model. However, by using flyweight, you can save memory, because instead of storing the same data everywhere, you just pass around an instance of flyweight, which Points to the same chunk of memory internally.<\/p>\n<p>Flyweight objects should be shared between models, allowing a very small amount of objects to be created, thereby preventing unnecessary memory usage. Sharing objects is a bit different from how the prototype pattern clones objects. Instead, a multiton should be used to make flyweight items and store them internally. Then the second time they are requested, the object in memory is returned.<\/p>\n<h3>When to Use the Flyweight Pattern<\/h3>\n<p>There are generally no scenarios in PHP when there is a need for a large number of shareable objects. As I mentioned above, the flyweight pattern is very prominent in game development and so the example I provide below will focus on a PHP game implementation.<\/p>\n<p><strong>Rules<\/strong><\/p>\n<ul>\n<li>Flyweight objects should never be created by the client using the new keyword. Instances should always be created using factory class.<\/li>\n<li>The factory class should store instances of each flyweight, similar to how a multiton stores a reference to an object in a static attribute.<\/li>\n<li>Flyweight attributes that are not shareable (external) between all instances of Flyweight must be supplied by the client and stored inside the Flyweight object.<\/li>\n<li>Flyweight attributes that are shareable (intrinsic) must be immutable and set by default to flyweight.<\/li>\n<li>The client\/controller is responsible for creating the flyweights using the factory class and providing them with the domain model.<\/li>\n<\/ul>\n<p>Effective use of flyweight patterns can provide memory consumption benefits.<br \/>\n<strong>Example:<\/strong><\/p>\n<p><code><?php\ninterface WeaponInterface\n{\n    public function __construct();\n    public function getBaseDamage();\n    public function getEnhancementsDamage();\n    public function getDamage();\n    public function reload();\n    public function addEnhancement(WeaponFlyweightInterface $enhancement);\n} \nclass PlasmaRifle implements WeaponInterface\n{   \n    const TOTAL_AMMO_IN_PLAMA_SHELL = 10;\n    const MIN_DAMAGE = 50;\n    const MAX_DAMAGE = 75; \n    private $ammoRemaining = null;\n    private $enhancements  = []; \n    public function __construct()\n    {\n        $this->reload();<br \/>\n    }<br \/>\n    public function getBaseDamage()<br \/>\n    {<br \/>\n        return rand(self::MIN_DAMAGE, self::MAX_DAMAGE);<br \/>\n    }<br \/>\n    public function getEnhancementsDamage()<br \/>\n    {<br \/>\n        $damage = 0;<br \/>\n        foreach($this->enhancements as $enhancement) {<br \/>\n            $damage += $enhancement->getDamage();<br \/>\n        }<br \/>\n        return $damage;<br \/>\n    }<br \/>\n    public function getDamage()<br \/>\n    {<br \/>\n        return  $this->getBaseDamage() + $this->getEnhancementsDamage();<br \/>\n    }<br \/>\n    public function reload()<br \/>\n    {<br \/>\n        $this->ammoRemaining = self::TOTAL_AMMO_IN_PLAMA_SHELL;<br \/>\n    }<br \/>\n    public function addEnhancement(WeaponFlyweightInterface $enhancement)<br \/>\n    {<br \/>\n        $this->enhancements[] = $enhancement;<br \/>\n    }<br \/>\n}<br \/>\ninterface WeaponFlyweightInterface<br \/>\n{<br \/>\n    public function getDamage();<br \/>\n}<br \/>\nclass PlasmaRifleGrenadeLauncherFlyweight implements WeaponFlyweightInterface<br \/>\n{<br \/>\n    const MIN_DAMAGE = 100;<br \/>\n    const MAX_DAMAGE = 120;<br \/>\n    public function getDamage()<br \/>\n    {<br \/>\n        return rand(self::MIN_DAMAGE, self::MAX_DAMAGE);<br \/>\n    }<br \/>\n}<br \/>\nclass PlasmaRifleExplosionFlyweight implements WeaponFlyweightInterface<br \/>\n{<br \/>\n    const MIN_DAMAGE = 500;<br \/>\n    const MAX_DAMAGE = 1000;<br \/>\n    public function getDamage()<br \/>\n    {<br \/>\n        return rand(self::MIN_DAMAGE, self::MAX_DAMAGE);<br \/>\n    }<br \/>\n}<br \/>\nclass PlasmaRifleFlyweightFactory<br \/>\n{<br \/>\n    private static $instances = [];<br \/>\n    public static function factory($flyweight)<br \/>\n    {<br \/>\n        $className = \"PlasmaRifle\" . $flyweight . \"Flyweight\";<br \/>\n        if(empty(self::$instances[$className])) {<br \/>\n            self::$instances[$className] = new $className();<br \/>\n        }<br \/>\n        return self::$instances[$className];<br \/>\n    }<br \/>\n}<br \/>\n$plasmaRifle = new PlasmaRifle();<br \/>\n$plasmaRifle->addEnhancement(PlasmaRifleFlyweightFactory::factory(\"GrenadeLauncher\"));<br \/>\n$plasmaRifle->addEnhancement(PlasmaRifleFlyweightFactory::factory(\"GrenadeLauncher\"));<br \/>\n$plasmaRifle->addEnhancement(PlasmaRifleFlyweightFactory::factory(\"GrenadeLauncher\"));<br \/>\n$plasmaRifle->addEnhancement(PlasmaRifleFlyweightFactory::factory(\"GrenadeLauncher\"));<br \/>\n$plasmaRifle->addEnhancement(PlasmaRifleFlyweightFactory::factory(\"GrenadeLauncher\"));<br \/>\n$plasmaRifle->addEnhancement(PlasmaRifleFlyweightFactory::factory(\"Explosion\"));<br \/>\n$plasmaRifle->addEnhancement(PlasmaRifleFlyweightFactory::factory(\"Explosion\"));<br \/>\n$plasmaRifle->addEnhancement(PlasmaRifleFlyweightFactory::factory(\"Explosion\"));<br \/>\n$plasmaRifle->addEnhancement(PlasmaRifleFlyweightFactory::factory(\"Explosion\"));<br \/>\n$plasmaRifle->addEnhancement(PlasmaRifleFlyweightFactory::factory(\"Explosion\"));<br \/>\n\/\/ Fire damage can vary wildly due to the random factor in base damage and flyweight enhancements<br \/>\necho \"Fire 1 Damage: \" . $plasmaRifle->getDamage(); # Fire 1 Damage: 3944<br \/>\necho \"Fire 2 Damage: \" . $plasmaRifle->getDamage(); # Fire 2 Damage: 4637<br \/>\necho \"Fire 3 Damage: \" . $plasmaRifle->getDamage(); # Fire 3 Damage: 4345<\/code><\/p>\n<p><small><em>If you have skills in PHP programming and you want to enhance your career in this field, a PHP certification from StudySection can help you reach your desired goals. Both beginner level and expert level <a href=\"https:\/\/www.studysection.com\/php-web-developer-advanced-diploma\">PHP Certification Exams<\/a> are offered by StudySection along with other programming certification exams.<\/em><\/small><\/p>\n","protected":false},"excerpt":{"rendered":"<p>The flyweight pattern is the structural pattern of today. Simply put, the Flyweight pattern is used to break down a<\/p>\n","protected":false},"author":1,"featured_media":5598,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[6],"tags":[763,200],"acf":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v21.7 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Flyweight Pattern in Php - StudySection Blog<\/title>\n<meta name=\"description\" content=\"Flyweight pattern is the structural pattern of today. Flyweights are used to store the common and repetitive data required by the model.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/studysection.com\/blog\/flyweight-pattern-in-php\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Flyweight Pattern in Php - StudySection Blog\" \/>\n<meta property=\"og:description\" content=\"Flyweight pattern is the structural pattern of today. Flyweights are used to store the common and repetitive data required by the model.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/studysection.com\/blog\/flyweight-pattern-in-php\/\" \/>\n<meta property=\"og:site_name\" content=\"Blog Posts on famous people, innovations and educational topics\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/studysection\" \/>\n<meta property=\"article:published_time\" content=\"2022-02-21T04:31:47+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2022-02-21T06:33:40+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/studysection.com\/blog\/wp-content\/uploads\/2022\/02\/Flyweight-Pattern.png\" \/>\n\t<meta property=\"og:image:width\" content=\"300\" \/>\n\t<meta property=\"og:image:height\" content=\"200\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"admin-studysection-blog\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@studysection\" \/>\n<meta name=\"twitter:site\" content=\"@studysection\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"admin-studysection-blog\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"2 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/studysection.com\/blog\/flyweight-pattern-in-php\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/studysection.com\/blog\/flyweight-pattern-in-php\/\"},\"author\":{\"name\":\"admin-studysection-blog\",\"@id\":\"https:\/\/studysection.com\/blog\/#\/schema\/person\/db367e2c29a12d1808fb1979edb3d402\"},\"headline\":\"Flyweight Pattern in Php\",\"datePublished\":\"2022-02-21T04:31:47+00:00\",\"dateModified\":\"2022-02-21T06:33:40+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/studysection.com\/blog\/flyweight-pattern-in-php\/\"},\"wordCount\":460,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/studysection.com\/blog\/#organization\"},\"keywords\":[\"Flyweight\",\"php\"],\"articleSection\":[\"Learn and Grow\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/studysection.com\/blog\/flyweight-pattern-in-php\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/studysection.com\/blog\/flyweight-pattern-in-php\/\",\"url\":\"https:\/\/studysection.com\/blog\/flyweight-pattern-in-php\/\",\"name\":\"Flyweight Pattern in Php - StudySection Blog\",\"isPartOf\":{\"@id\":\"https:\/\/studysection.com\/blog\/#website\"},\"datePublished\":\"2022-02-21T04:31:47+00:00\",\"dateModified\":\"2022-02-21T06:33:40+00:00\",\"description\":\"Flyweight pattern is the structural pattern of today. Flyweights are used to store the common and repetitive data required by the model.\",\"breadcrumb\":{\"@id\":\"https:\/\/studysection.com\/blog\/flyweight-pattern-in-php\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/studysection.com\/blog\/flyweight-pattern-in-php\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/studysection.com\/blog\/flyweight-pattern-in-php\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/studysection.com\/blog\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Flyweight Pattern in Php\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/studysection.com\/blog\/#website\",\"url\":\"https:\/\/studysection.com\/blog\/\",\"name\":\"Blog Posts on famous people, innovations and educational topics\",\"description\":\"\",\"publisher\":{\"@id\":\"https:\/\/studysection.com\/blog\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/studysection.com\/blog\/?s={search_term_string}\"},\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/studysection.com\/blog\/#organization\",\"name\":\"StudySection\",\"url\":\"https:\/\/studysection.com\/blog\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/studysection.com\/blog\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/studysection.com\/blog\/wp-content\/uploads\/2021\/10\/studySection-logo.png\",\"contentUrl\":\"https:\/\/studysection.com\/blog\/wp-content\/uploads\/2021\/10\/studySection-logo.png\",\"width\":920,\"height\":440,\"caption\":\"StudySection\"},\"image\":{\"@id\":\"https:\/\/studysection.com\/blog\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/studysection\",\"https:\/\/twitter.com\/studysection\",\"https:\/\/www.instagram.com\/study.section\/\",\"https:\/\/www.linkedin.com\/company\/studysection\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/studysection.com\/blog\/#\/schema\/person\/db367e2c29a12d1808fb1979edb3d402\",\"name\":\"admin-studysection-blog\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/studysection.com\/blog\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/054ac87a6874df1932004239cd8eab36?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/054ac87a6874df1932004239cd8eab36?s=96&d=mm&r=g\",\"caption\":\"admin-studysection-blog\"},\"url\":\"https:\/\/studysection.com\/blog\/author\/admin-studysection-blog\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Flyweight Pattern in Php - StudySection Blog","description":"Flyweight pattern is the structural pattern of today. Flyweights are used to store the common and repetitive data required by the model.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/studysection.com\/blog\/flyweight-pattern-in-php\/","og_locale":"en_US","og_type":"article","og_title":"Flyweight Pattern in Php - StudySection Blog","og_description":"Flyweight pattern is the structural pattern of today. Flyweights are used to store the common and repetitive data required by the model.","og_url":"https:\/\/studysection.com\/blog\/flyweight-pattern-in-php\/","og_site_name":"Blog Posts on famous people, innovations and educational topics","article_publisher":"https:\/\/www.facebook.com\/studysection","article_published_time":"2022-02-21T04:31:47+00:00","article_modified_time":"2022-02-21T06:33:40+00:00","og_image":[{"width":300,"height":200,"url":"https:\/\/studysection.com\/blog\/wp-content\/uploads\/2022\/02\/Flyweight-Pattern.png","type":"image\/png"}],"author":"admin-studysection-blog","twitter_card":"summary_large_image","twitter_creator":"@studysection","twitter_site":"@studysection","twitter_misc":{"Written by":"admin-studysection-blog","Est. reading time":"2 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/studysection.com\/blog\/flyweight-pattern-in-php\/#article","isPartOf":{"@id":"https:\/\/studysection.com\/blog\/flyweight-pattern-in-php\/"},"author":{"name":"admin-studysection-blog","@id":"https:\/\/studysection.com\/blog\/#\/schema\/person\/db367e2c29a12d1808fb1979edb3d402"},"headline":"Flyweight Pattern in Php","datePublished":"2022-02-21T04:31:47+00:00","dateModified":"2022-02-21T06:33:40+00:00","mainEntityOfPage":{"@id":"https:\/\/studysection.com\/blog\/flyweight-pattern-in-php\/"},"wordCount":460,"commentCount":0,"publisher":{"@id":"https:\/\/studysection.com\/blog\/#organization"},"keywords":["Flyweight","php"],"articleSection":["Learn and Grow"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/studysection.com\/blog\/flyweight-pattern-in-php\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/studysection.com\/blog\/flyweight-pattern-in-php\/","url":"https:\/\/studysection.com\/blog\/flyweight-pattern-in-php\/","name":"Flyweight Pattern in Php - StudySection Blog","isPartOf":{"@id":"https:\/\/studysection.com\/blog\/#website"},"datePublished":"2022-02-21T04:31:47+00:00","dateModified":"2022-02-21T06:33:40+00:00","description":"Flyweight pattern is the structural pattern of today. Flyweights are used to store the common and repetitive data required by the model.","breadcrumb":{"@id":"https:\/\/studysection.com\/blog\/flyweight-pattern-in-php\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/studysection.com\/blog\/flyweight-pattern-in-php\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/studysection.com\/blog\/flyweight-pattern-in-php\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/studysection.com\/blog\/"},{"@type":"ListItem","position":2,"name":"Flyweight Pattern in Php"}]},{"@type":"WebSite","@id":"https:\/\/studysection.com\/blog\/#website","url":"https:\/\/studysection.com\/blog\/","name":"Blog Posts on famous people, innovations and educational topics","description":"","publisher":{"@id":"https:\/\/studysection.com\/blog\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/studysection.com\/blog\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/studysection.com\/blog\/#organization","name":"StudySection","url":"https:\/\/studysection.com\/blog\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/studysection.com\/blog\/#\/schema\/logo\/image\/","url":"https:\/\/studysection.com\/blog\/wp-content\/uploads\/2021\/10\/studySection-logo.png","contentUrl":"https:\/\/studysection.com\/blog\/wp-content\/uploads\/2021\/10\/studySection-logo.png","width":920,"height":440,"caption":"StudySection"},"image":{"@id":"https:\/\/studysection.com\/blog\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/studysection","https:\/\/twitter.com\/studysection","https:\/\/www.instagram.com\/study.section\/","https:\/\/www.linkedin.com\/company\/studysection"]},{"@type":"Person","@id":"https:\/\/studysection.com\/blog\/#\/schema\/person\/db367e2c29a12d1808fb1979edb3d402","name":"admin-studysection-blog","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/studysection.com\/blog\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/054ac87a6874df1932004239cd8eab36?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/054ac87a6874df1932004239cd8eab36?s=96&d=mm&r=g","caption":"admin-studysection-blog"},"url":"https:\/\/studysection.com\/blog\/author\/admin-studysection-blog\/"}]}},"views":277,"_links":{"self":[{"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/posts\/5597"}],"collection":[{"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/comments?post=5597"}],"version-history":[{"count":3,"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/posts\/5597\/revisions"}],"predecessor-version":[{"id":5602,"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/posts\/5597\/revisions\/5602"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/media\/5598"}],"wp:attachment":[{"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/media?parent=5597"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/categories?post=5597"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/studysection.com\/blog\/wp-json\/wp\/v2\/tags?post=5597"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}