<?php
function getNestedValue($array, $path, $separator = '.') {
$keys = explode($separator, $path);
foreach ($keys as $key) {
if (isset($array[$key])) {
$array = $array[$key];
} else {
return null; // nebo hodnotu podle vašich potřeb
}
}
return $array;
}
$x = [
'a' => [
'b' => [
'c' => 'FINAL C ... ;)'
],
],
];
echo getNestedValue($x, 'a.b.c');
<?php
class Record {
private $data = [];
private $currentIndex = 0;
public function addRecord($value) {
$this->data[] = $value;
}
public function getRecord() {
if ($this->currentIndex < count($this->data)) {
$record = $this->data[$this->currentIndex];
$this->currentIndex++;
return $record;
} else {
return null;
}
}
}
// Vytvoření instance třídy
$recordKeeper = new Record();
// Přidání záznamů
$recordKeeper->addRecord("John");
$recordKeeper->addRecord(30);
$recordKeeper->addRecord("New York");
// Získání a postupné procházení všech záznamů pomocí cyklu foreach a metody getRecord()
echo "All records:<br>";
while ($record = $recordKeeper->getRecord()) {
echo $record . "<br>";
}
<?php
function generatorFunction() {
yield 1;
yield 2;
yield 3;
}
// Použití generátoru
$generator = generatorFunction();
foreach ($generator as $value) {
echo $value . ' ';
}
// Výstup: 1 2 3
/* ----------------------------- */
names.txt
===
John Doe
Jane Smith
Bob Johnson
Alice Williams
... (a mnoho dalších jmen)
function readNamesFromFile($filename) {
$file = fopen($filename, 'r');
if (!$file) {
throw new Exception("Nepodařilo se otevřít soubor.");
}
while (($line = fgets($file)) !== false) {
yield trim($line);
}
fclose($file);
}
// Použití generátoru pro zpracování jmen ze souboru
$generator = readNamesFromFile('names.txt');
foreach ($generator as $name) {
// Provádění operace s každým jménem
echo "Hello, $name!" . PHP_EOL;
}
/* ----------------------------- */
function randomDataGenerator($count) {
for ($i = 0; $i < $count; $i++) {
yield rand(1, 100); // Generujeme náhodné číslo v rozmezí 1 až 100
}
}
// Generujeme 10 náhodných čísel
$generator = randomDataGenerator(10);
foreach ($generator as $number) {
// Provádění operace s každým náhodným číslem
echo $number . ' ';
}
/* ----------------------------- */
function searchValueInArray(array $array, $value) {
foreach ($array as $item) {
if (in_array($value, $item)) {
yield $item;
}
}
}
// Příklad použití:
$data = array(
array('id' => 1, 'name' => 'John'),
array('id' => 2, 'name' => 'Jane'),
array('id' => 3, 'name' => 'Bob'),
array('id' => 4, 'name' => 'Alice')
);
$searchValue = 'Bob';
foreach (searchValueInArray($data, $searchValue) as $result) {
echo "Hodnota nalezena: " . $result['name'] . "\n";
}
// Staré rozhraní
class OldCar {
getSpeedInMPH() {
return 60;
}
}
// Nové rozhraní
class NewCar {
getSpeedInKPH() {
return 100;
}
}
class CarAdapter {
constructor(newCar) {
this.newCar = newCar;
}
// Adapter převede metodu getSpeedInMPH() na metodu getSpeed() pro kompatibilitu
getSpeed() {
return this.convertMPHtoKPH(this.newCar.getSpeedInKPH());
}
convertMPHtoKPH(mph) {
return mph * 1.60934;
}
}
const newCar = new NewCar();
const adaptedCar = new CarAdapter(newCar);
console.log("Nové auto (v KPH):", newCar.getSpeedInKPH()); // Vypíše "Nové auto (v KPH): 100"
console.log("Staré auto (v MPH):", adaptedCar.getSpeed()); // Vy
// We declare our prototype object with two methods
const enemy = {
attack: () => console.log("Pim Pam Pum!"),
flyAway: () => console.log("Flyyyy like an eagle!")
}
// We declare another object that will inherit from our prototype
const bug1 = {
name: "Buggy McFly",
phrase: "Your debugger doesn't work with me!"
}
// With setPrototypeOf we set the prototype of our object
Object.setPrototypeOf(bug1, enemy)
// With getPrototypeOf we read the prototype and confirm the previous has worked
console.log(Object.getPrototypeOf(bug1)) // { attack: [Function: attack], flyAway: [Function: flyAway] }
console.log(bug1.phrase) // Your debugger doesn't work with me!
console.log(bug1.attack()) // Pim Pam Pum!
console.log(bug1.flyAway()) // Flyyyy like an eagle!
// Abstraktní třída definující Factory Method
class AnimalFactory {
createAnimal() {
throw new Error("Metoda createAnimal musí být implementována.");
}
}
// Konkrétní třída implementující Factory Method
class DogFactory extends AnimalFactory {
createAnimal() {
return new Dog();
}
}
class CatFactory extends AnimalFactory {
createAnimal() {
return new Cat();
}
}
// Abstraktní třída reprezentující objekty, které budeme vytvářet
class Animal {
makeSound() {
throw new Error("Metoda makeSound musí být implementována.");
}
}
// Konkrétní třídy reprezentující objekty, které budeme vytvářet
class Dog extends Animal {
makeSound() {
console.log("Haf haf!");
}
}
class Cat extends Animal {
makeSound() {
console.log("Mňau mňau!");
}
}
// Použití Factory Method Pattern
function createAndMakeSound(animalFactory) {
const animal = animalFactory.createAnimal();
animal.makeSound();
}
// Použití Factory Method Pattern s různými Factory
const dogFactory = new DogFactory();
const catFactory = new CatFactory();
createAndMakeSound(dogFactory); // Vypíše "Haf haf!"
createAndMakeSound(catFactory); // Vypíše "Mňau mňau!"
class Singleton {
static instance = null;
constructor() {
if (Singleton.instance) {
throw new Error("Singleton instance already exists. Use getInstance() method to access it.");
}
// Inicializace Singletonu zde
}
static getInstance() {
if (!Singleton.instance) {
Singleton.instance = new Singleton();
}
return Singleton.instance;
}
someMethod() {
console.log("Metoda Singletonu");
}
}
// Použití Singletonu
const singletonInstance1 = Singleton.getInstance();
const singletonInstance2 = Singleton.getInstance(); // Tady bude vyvolána chyba
console.log(singletonInstance1 === singletonInstance2); // Vrátí true, protože se jedná o stejnou instanci
singletonInstance1.someMethod(); // Vypíše "Metoda Singletonu"
/*
URL: https://learn.coderslang.com/0076-javascript-design-patterns-builder/
*/
// how create object from literal
const Employee = {
isAdmin: false,
getRole: function() {
return this.isAdmin ? 'Admin' : 'RegularEmp';
};
};
const emp1 = Object.create(Employee);
emp1.getRole(); //'RegularEmp'
const emp2 = Object.create(Employee);
emp2.isAdmin = true;
emp2.getRole(); //'Admin'
// BUILDER PATTERN (prenasi a pomaha tvorit objekty s mandatory parametry, nepovinne vytvori separatne)
class OTG {
constructor(model, color, maxTemperature, maxTimeSelection) {
this.model = model;
this.title = 'OTG';
this.color = color;
this.maxTemperature = maxTemperature || 150;
this.maxTimeSelection = maxTimeSelection || 30;
}
}
const redOTG = new OTG('LG', 'red');
const highTempOTG = new OTG('LG', 'black', 200);
const highendTimeOTG = new OTG('LG', 'red', '150', '60');
class OTGBuilder {
constructor(model, color) {
this.model = model;
this.title = 'OTG';
this.color = color;
}
setMaxTemperature(temp) {
this.maxTemperature = temp;
return this;
}
setMaxTimeSelection(maxTime) {
this.maxTimeSelection = maxTime;
return this;
}
build() {
return new OTG(this.model, this.color,
this.maxTemperature, this.maxTimeSelection);
}
}
const basicOTG = new OTGBuilder('MorphyRichards', 'Black')
.setMaxTemperature(250)
.setMaxTimeSelection(60)
.build();
// or without mandatory params
const default = new OTGBuilder('Generic OTG', 'White')
.build();
/*
URL: https://learn.coderslang.com/0116-javascript-design-patterns-decorator/
*/
class Headphone {
constructor(model, color) {
this.model = model;
this.color = color;
}
getPrice() {
return 100;
}
}
class WirelessHeadPhone extends Headphone {
constructor(model, color) {
super(model, color);
this.isWired = false;
}
getPrice() {
return 150;
}
}
class WaterproofHeadPhone extends Headphone {
constructor(model, color) {
super(model, color);
this.isWaterproof = true;
}
getPrice() {
return 120;
}
}
class WaterProofAndWirelessHeadphone extends Headphone {
constructor(model, color) {
super(model, color);
this.isWaterproof = true;
this.isWired = false;
}
getPrice() {
return 170;
}
}
class BabyEarHeadphone extends Headphone {
constructor() {
super(model, color);
this.size = 'Small';
}
getPrice() {
return 80;
}
}
<?php
class OrderAction extends FrontControl
{
public function __construct(,
Order $order,
Model\OrderAction $orderAction,
Container $container
)
{
parent::__construct();
$this->order = $order;
$this->orderAction = $orderAction;
$this->actions = $this->orderAction->getActions($this->pageByState);
}
public function render(array $config = [])
{
$config = $this->getCurrentConfig($config);
$this->template->order = $this->order;
$this->template->actions = $this->actions;
$this->vueRender($config);
}
public function createComponent(string $name): ?Nette\ComponentModel\IComponent
{
if (!Strings::startsWith($name, 'action')) {
return parent::createComponent($name);
}
return $this->container->createInstance('App\\FrontModule\\Components\\' . $this->actions[Strings::after($name, 'action')]->action, [
'orderAction' => $this->actions[Strings::after($name, 'action')],
'order' => $this->order
]);
}
}