PHP code example of blabs-dev / php-dictionary

1. Go to this page and download the library: Download blabs-dev/php-dictionary library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

blabs-dev / php-dictionary example snippets


// create a class extending the Dictionary abstract

use Blabs\Dictionary\Dictionary;

class Fruits extends Dictionary
{
    const APPLE = 'apple';
    const BANANA = 'banana';
    const ORANGE = 'orange';
}


// return all "values" from the dictionary

Fruits::values() // outputs [ 'apple', 'banana', 'orange' ]

// check if a value is valid

Fruits::isValid('apple') // outputs `true`

Fruits::isValid('tomato') // outputs `false`

use Blabs\Dictionary\WithDictionary; 

class MyVegetablesWarehouse extends StockService
{
    use WithDictionary;  // weet pepper';
    const TOMATO = 'tomato';
    
    // Checks if a product is a "legit" vegetable :)   
    public function isVegetable($product)
    {
        // recalls dictionary trait method to check if the dictionary has specified product
        return self::isValid($product);  
    }
    
    // Lists all available vegetables  
    public function getVegetables()
    {
        // recalls dictionary static method to list all vegetable products
        return self::values(); 
    }
    
    // Get stocks for a specific vegetable
    public function getVegetablesStocks($vegetable)
    {
        // uses dictionary static method to check if the product is "valid" before doing anything else
        if (! self::isValid($vegetable))   
            throw new InvalidArgumentException('this is not a veggie!')
            
        // then recalls a hypothetical method from elsewhere (i.e. the StockService class)
        return $this->getStocks($vegetable); 
    }
    
    // Creates an "inventory" array
    public function getVegetablesInventory()
    {        
        $stocks = [];
        
        foreach (self::values() as $vegetable)  // cycle all vegetables in the dictionary
        {
            $stocks[$vegetable] = $this->getStocks($vegetable);
        }
        
        return $stocks;
    }
}


// the class will still expose static methods outside its context

MyVegetablesWarehouse::values() // outputs [ 'aubergine', 'sweet pepper', 'tomato' ]


// check if a value is valid

MyVegetablesWarehouse::isValid('apple') // outputs `false`

MyVegetablesWarehouse::isValid('tomato') // outputs `true`