public function testChangeUserName() { /* * Wir definieren welche Tabellen verwendet werden sollen. Dies kann auch in einer setUp() für die ganze Klasse erfolgen. */ $this->tables = ['users']; /* * Aufbau der DB-Verbindung. */ /** @var \PDO $db */ $db = $this->getDb(); /* * Seed eines Datensatzes in die Tabelle. */ $db->exec('INSERT INTO users (id, username) VALUES (2, "old name")'); /* * Normaler Testaufruf. */ $class = new ExampleClass($db); $class->changeUserName(2, 'new name'); /* * Laden des Datensatzes und Prüfen der erwarteten Änderungen. */ $user = $db->query('SELECT * FROM users WHERE id = 2')->fetchObject(); $this->assertEquals('new name', $user->username); }
/** * @depends testConstruct * * @param ExampleClass $class */ public function testProcessData(ExampleClass $class) { /* * Ein abhängiger Test muss als Parameter den Rückgabewert des Vorgängers akzeptieren. */ $class->processData(); }
public function verifyWithAMock() { $mock = \Enhance\MockFactory::createMock('ExampleDependencyClass'); $mock->addExpectation(\Enhance\Expect::method('getSomething')->with(1, 'Arg2')->returns('Something')->times(1)); $target = new ExampleClass($mock); $result = $target->doSomething(); $mock->verifyExpectations(); }
public function testOutputTricky() { $class = new ExampleClass(); ob_start(); $class->output(); $output = ob_get_clean(); $this->assertTrue(stripos($output, 'OK') !== false); }
public function testReloadMethodWithArgAdded() { $this->loadBaseClass(); $class = new ExampleClass(); $this->assertEquals('original', $class->addArg()); $this->overwriteBaseClass(); $res = SMC::reload_method('ExampleClass', 'exampleArgDefault'); $this->assertTrue($res); $this->assertEquals('changedargmeth', $class->exampleArgDefault('changedargmeth')); }
function some_endpoint() { //when there are many parameters for a method call, keeping them in order with an array of keys is easier to read $keys = array('currentPost', 'paged', 'post_type', 'vertical', 'posts_per_page'); //Maps keys to incoming parameters if ($args = array_combine($keys, func_get_args())) { array_walk($args, array($this, 'empty_defaults')); $response = ExampleClass::some_data_method($args); return $response; } else { return array('Parameters mismatch'); } }
// Создаем дочерний процесс $child_pid = pcntl_fork(); if ($child_pid) { // Выходим из родительского процесса, привязанного к консоли... exit(0); } // Делаем основным процессом дочерний... posix_setsid(); // Включаем тики, в противном случае скрипт просто повисает и не реагирует на внешние раздражители... declare (ticks=1); // Здесь я подключаю всякую нужную штуку... include __DIR__ . '/Daemon.php'; include __DIR__ . '/ExampleClass.php'; // Класс изображающий полезную нагрузку... $example = new ExampleClass(); // Именно эта функция делает всякую полезую нам нагрузку, которую мы хотим демонизировать... // Если нам нужны какие-нибудь классы не забываем упомянуть их тут в противном случае простоо не получите к ним доступ... $func = function () use($example) { // Тут живёт всякая полезная нагрука... $example->test(); return true; }; // Собственно создаём демона, соответственно говорим ему куда записывать свой pid... $daemon = new Daemon('/tmp/daemon.pid'); // Закрываем порочные связи со стандартным вводом-выводом... fclose(STDIN); fclose(STDOUT); fclose(STDERR); // Перенаправляем ввод-вывод туда куда нам надо или не надо... $STDIN = fopen('/dev/null', 'r');
public function addTwoNumbersWith4and0Expect4() { $result = $this->target->addTwoNumbers(4, 0); \Enhance\Assert::areIdentical(4, $result); }
require __DIR__ . '/../vendor/autoload.php'; require 'ExampleClass.php'; $console = new AuronConsultingOSS\Logger\Console(); // Straight string messages $console->info('This is an info message'); $console->notice('This is a notice message'); $console->debug('This is a debug message'); $console->warning('This is a warning message'); $console->alert('This is an alert message'); $console->error('This is an error message'); $console->emergency('This is an emergency message'); $console->critical('This is a critical message'); // Messages with exceptions and traces try { $exampleClass = new ExampleClass(); $exampleClass->prepare(); } catch (Exception $ex) { $console->error('Whoopsies', ['exception' => $ex]); } // Messages with random data $console->warning('Some data on context', ['foo' => 'bar']); // Messages with random data plus exception $console->alert('Some data on context, as well as an exception', ['foo' => 'bar', 'exception' => $ex]); // Passing on an exception directly as a message (or any object that implements __toString) $console->debug($ex); // Since we're PSR-3, we can be injected on objects that understand LoggerAwareInterface - example class does $exampleClass->setLogger($console); $exampleClass->runLoggerAwareExample(); // You get the idea $console->notice('That\'s it.');
/** * */ public function testAssertArrayableReturn() { $o = new ExampleClass(); $this->assertContainsOnly('string', $o->toArray()); }
require_once 'php_examples_5_ExampleClass.php'; // Instantiate the ExampleClass print_example_count($example_count++, __LINE__); $my_example = new ExampleClass('Jason', 'Astronauts', 'John'); // Using echo on $my_example will cause the __toString() method to be called // to typecast the $my_example instance as a string. echo $my_example . "\n"; // Let's create another instance of ExampleClass without specifying // the group name or your name. print_example_count($example_count++, __LINE__); $another_example = new ExampleClass('Jason'); echo $another_example . "\n"; // Let's create another instance of ExampleClass but pass in // null for for my name. print_example_count($example_count++, __LINE__); $yet_another_example = new ExampleClass(null, 'Astronauts', 'John'); echo $yet_another_example . "\n"; // Let's set the my name for the instance we just created. print_example_count($example_count++, __LINE__); $yet_another_example->my_name = 'Jason'; echo $yet_another_example . "\n"; // Let's change my group to Mission Control. Since it is protected, // we must use a setter. print_example_count($example_count++, __LINE__); $yet_another_example->setGroupName('Mission Control'); echo $yet_another_example . "\n"; // Let's change your name to Jill. We must use a setter to do that // since it is private. print_example_count($example_count++, __LINE__); $yet_another_example->setYourName('Jill'); echo $yet_another_example . "\n";
<?php array_fill_keys(); ExampleClass::array_fill_keys();
<?php namespace Framework\Utilities; require "../autoload.php"; require "ExampleClass.php"; $example_obj = new ExampleClass(); //$example_obj->AuthenticationTest(); //$example_obj->EncryptionTest(); //$example_obj->CachingTest(); //$example_obj->DatabaseTest(); //$example_obj->ExcelTest(); //$example_obj->EmailTest(); //$example_obj->ErrorHandlingTest(); //$example_obj->FileSystemTest(); $example_obj->StringTest(); //$example_obj->TemplateTest(); //$example_obj->ReflectionTest(); //$example_obj->LoggingTest(); //$example_obj->ProfilingTest();
<?php namespace Framework\Utilities; require "../autoload.php"; require "ExampleClass.php"; $example_obj = new ExampleClass(); //$example_obj->AuthenticationTest(); //$example_obj->EncryptionTest(); $example_obj->CachingTest(); //$example_obj->DatabaseTest(); //$example_obj->ExcelTest(); //$example_obj->EmailTest(); //$example_obj->ErrorHandlingTest(); //$example_obj->FileSystemTest(); //$example_obj->StringTest(); //$example_obj->TemplateTest(); //$example_obj->ReflectionTest(); //$example_obj->LoggingTest(); //$example_obj->ProfilingTest();
<?php require '../lib/init.php'; define('CACHE_DATA_FOLDER', dirname(__FILE__) . "/cache-folder"); use Hybrid\Cache; use Hybrid\storages\Disk as DiskStorage; class ExampleClass { use Hybrid\Cacheable; public function heavyProcess() { if ($cacheData = $this->isCached(__FILE__, __METHOD__)) { return $cacheData; } // heavy proccess: sleep(3); $data = md5(microtime()); return $this->saveCache($data, __FILE__, __METHOD__); } } echo "Generating data (firt time)\n"; $ins = new ExampleClass(); echo "data: " . $ins->heavyProcess() . "\n"; echo "Generating data (second time)\n"; $insb = new ExampleClass(); echo "data: " . $insb->heavyProcess() . "\n";
<?php require "vendor/autoload.php"; use Facepunch\Facepunch as FacepunchController; class ExampleClass { protected $facepunch; public function __construct() { $this->facepunch = new FacepunchController(); } public function getUsername($userid) { $this->facepunch->setUserID($userid); if (!$this->facepunch->isUserValid()) { return false; } return $this->facepunch->getUsername(); } } //Create Class $example = new ExampleClass(); //Echo it out echo $example->getUsername('1');