computed: {
fullName: {
// геттер:
get: function () {
return this.firstName + ' ' + this.lastName
},
// сеттер:
set: function (newValue) {
var names = newValue.split(' ')
this.firstName = names[0]
this.lastName = names[names.length - 1]
}
}
}
$params = [];
$sql = "SELECT * FROM `brands` ";
if (!empty($_GET['district'])) {
$sql .= "WHERE `district` = ?";
$params[] = $_GET['district'];
}
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
function group(data, key, val = n => n) {
const getKey = key instanceof Function ? key : n => n[key];
const getVal = val instanceof Function ? val : n => n[val];
const grouped = {};
for (const n of data) {
const k = getKey(n);
(grouped[k] = grouped[k] || []).push(getVal(n));
}
return grouped;
}
group(arr, 'room')
// или
group(arr, n => n.room)
group(Array(5).keys(), n => n % 2 ? 'нечётные' : 'чётные')
group('a8-C!39', n => (
n.toLowerCase() !== n.toUpperCase() ? 'буква' :
!Number.isNaN(+n) ? 'цифра' :
'другое'
))
<input name="xxx" value="69">
<input name="xxx" value="187">
<input name="xxx" value="666">
<input name="yyy" value="-1">
group(document.querySelectorAll('input'), 'name', n => +n.value)
const asyncForEach = (data, callback) =>
Array.prototype.reduce.call(
data,
(promise, n, i, a) => promise.then(() => callback(n, i, a)),
Promise.resolve()
).then(() => {});
// или
async function asyncForEach(data, callback) {
for (let i = 0; i < data.length; i++) {
await callback(data[i], i, data);
}
}
asyncForEach(
document.querySelectorAll('li'),
li => new Promise(r => setTimeout(() => r(console.log(li.textContent)), 1000))
);
SELECT * FROM table_name
WHERE date_column > (SELECT MAX(date_column) FROM table_name WHERE counter = 0)
я про то что данные передаются через конструктор . Ведь можно просто в самом коде их определить того же файлаВ конструктор в данном случае передаются на данные, а объект, который будет строить запросы. Это же класс репозитория - он инкапсулирует запросы к БД, но пользуется при этом моделями Eloquent.
class PortfoliosRepository extends Repository {
public function __construct(Portfolio $portfolio) {
$this->model = $portfolio;
}
// Этот метод, скорее всего, есть в базовом классе
public function find(int $id): ?Portfolio
{
return $this->model->find($id);
}
// А это пример инкапсуляции сложной логики
public function featured(): Collection
{
return $this->model
->with(['some', 'relations'])
->where('field', 'value')
->orWhere('other_field', 'value')
->orderBy('created_at')
->limit(42)
->get()
->each
->append('mutated_attribute');
}
}
$repository = new PortfoliosRepository(
new Portfolio // <- не какое-то существующее портфолио из БД, а "пустой" объект
);
$repository->featured();
function startAfter (delay, callback) {
const elapsed = Date.now() - performance.timing.navigationStart
if (elapsed >= delay) {
callback()
} else {
setTimeout(callback, delay - elapsed)
}
}
document.addEventListener("DOMContentLoaded", () => {
startAfter(2000, () => console.log("DOM fully loaded and parsed"))
})
namespace App\Contract;
interface PaymentInterface
{
public function pay(): string;
}
namespace App\Service;
use App\Contract\PaymentInterface;
class Payment implements PaymentInterface
{
protected $paymentLink;
public function __construct($paymentLink)
{
$this->paymentLink = $paymentLink;
}
public function pay(): string
{
return (string)$this->paymentLink;
}
}
namespace App\Providers;
use App\Contract\PaymentInterface;
use App\Service\Payment;
use Illuminate\Support\ServiceProvider;
class PaymentProvider extends ServiceProvider
{
/**
* Register services.
*
* @return void
*/
public function register()
{
$this->app->bind(PaymentInterface::class, function ($app) {
return new Payment(config('app.payment_link'));
});
}
/**
* Bootstrap services.
*
* @return void
*/
public function boot()
{
//
}
}
App\Providers\PaymentProvider::class,
'payment_link' => 'https://money.yandex.ru’,
namespace App\Http\Controllers;
use App\Contract\PaymentInterface;
class PaymentController
{
public function getPayment(PaymentInterface $payment)
{
dd($payment->pay());
}
}