All authors

Claude Skills by HoangNguyen0403
github.com/HoangNguyen04031,434 skills30 installs1,975 views
- Php ConcurrencyUse PHP 8.1 Fibers for cooperative concurrency, and let an event loop or scheduler decide when to resume them: ~~~php $fiber = new Fiber(function (): string { Fiber::suspend('waiting'); return 'done'; }); $fiber->start(); $fiber->resume(); $result = $fiber->getReturn(); ~~~ Catch failures around the Fiber boundary, keep state isolated, and use a separate PDO connection per Fiber when database work is involved.Votes: 0GitHub stars: 549
- Php ConcurrencyUse ReactPHP or Amp for non-blocking I/O and run the event loop at the application entry point. Use async-compatible clients; do not call blocking file_get_contents or sleep inside a Fiber or event loop. Propagate errors through the library's promise or future mechanism.Votes: 0GitHub stars: 549
- Php ConcurrencyUse ReactPHP's event loop and promise-based APIs for async work: ~~~php $loop = Loop::get(); $promise = $client->request('https://example.com'); $promise->then( static fn (ResponseInterface $response): void => $handle($response), static fn (Throwable $error): void => $logger->error('Request failed', ['exception' => $error]), ); Loop::run(); ~~~ Use non-blocking libraries, handle rejection, and avoid custom schedulers or blocking calls.Votes: 0GitHub stars: 549
- Php ConcurrencyIn PHP 8.1, Fiber::suspend() yields control to the caller and the value passed to resume() becomes the return value of the suspend call: ~~~php $fiber = new Fiber(function (): string { $input = Fiber::suspend('paused'); return 'received ' . $input; }); $fiber->start(); $fiber->resume('hello'); $output = $fiber->getReturn(); ~~~ Resume only a started, suspended Fiber and handle exceptions at the boundary.Votes: 0GitHub stars: 549
- Php ConcurrencyUse Guzzle's Pool or ReactPHP's HTTP client rather than sequential blocking calls: ~~~php $pool = new Pool($client, $requests, [ 'concurrency' => 10, 'fulfilled' => static fn (ResponseInterface $response): void => $collect($response), 'rejected' => static fn (Throwable $error): void => $logger->error('HTTP failed', ['exception' => $error]), ]); $pool->promise()->wait(); ~~~ Bound concurrency, collect failures, and use an async-compatible client.Votes: 0GitHub stars: 549
- Php ConcurrencyUse an async database client or one Fiber per query, with a separate PDO connection for each Fiber. Do not share mutable connection state across Fibers and do not run blocking PDO calls inside an event loop unless they are isolated in an appropriate worker. Bound concurrency, aggregate results, and propagate each query's exception.Votes: 0GitHub stars: 549
- Php Error HandlingCatch specific exceptions when recovery is possible and use Throwable at an application boundary: ~~~php try { $user = $service->load($id); } catch (NotFoundException $e) { return Response::notFound(); } catch (Throwable $e) { $logger->error('User load failed', ['exception' => $e]); throw $e; } ~~~ Prefer throwing domain exceptions over returning false or null for errors, never leave a catch block empty, and use finally for cleanup.Votes: 0GitHub stars: 549
- Php Error HandlingCreate a domain-specific exception that extends an SPL runtime exception: ~~~php final class UserNotFound extends RuntimeException { public function __construct(int $userId) { parent::__construct("User not found: {$userId}"); } } ~~~ Throw it for the domain failure and catch it at the layer that can translate it into a response or recovery action. Preserve the previous exception when wrapping lower-level failures.Votes: 0GitHub stars: 549
- Php Error HandlingRegister a top-level handler that accepts Throwable, logs structured context, and performs final cleanup: ~~~php set_exception_handler(static function (Throwable $error) use ($logger): void { $logger->critical('Unhandled exception', ['exception' => $error]); http_response_code(500); echo 'Internal Server Error'; }); ~~~ Pair it with a deliberate set_error_handler strategy where needed, keep display_errors off and log_errors on in production, and do not expose stack traces.Votes: 0GitHub stars: 549
- Php Error HandlingCatch Throwable when a boundary must handle both PHP Error instances and Exception instances: ~~~php try { $result = $handler->run(); } catch (Throwable $error) { $logger->error('Operation failed', ['exception' => $error]); throw $error; } ~~~ Use narrower exception catches when possible, never suppress the failure silently, and reserve recovery for errors the application can safely handle.Votes: 0GitHub stars: 549
- Php Error HandlingDepend on Psr\Log\LoggerInterface and log exceptions with structured context: ~~~php try { $service->run($id); } catch (Throwable $error) { $logger->error('Service operation failed', [ 'operation' => 'run', 'entity_id' => $id, 'exception' => $error, ]); throw $error; } ~~~ Use the appropriate PSR-3 level and exclude passwords, tokens, and other sensitive values from context.Votes: 0GitHub stars: 549
- Php Error HandlingPut cleanup in finally so it runs after success, an exception, or an early return: ~~~php $handle = fopen($path, 'rb'); try { return $this->read($handle); } finally { fclose($handle); } ~~~ Use finally for file handles, transactions, and other resources; log or rethrow failures rather than hiding them.Votes: 0GitHub stars: 549
- Php LanguageUse match for value mapping because it uses strict comparison and is exhaustive: ~~~php $statusLabel = match ($status) { 'pending' => 'Waiting', 'paid' => 'Complete', 'failed' => 'Failed', default => throw new InvalidArgumentException("Unknown status: {$status}"), }; ~~~ Return the expression directly where possible and provide a deliberate default for unknown values.Votes: 0GitHub stars: 549
- Php LanguageDeclare immutable constructor state with a PHP 8.1 readonly property: ~~~php final class User { public function __construct( public readonly string $id, ) { } } ~~~ A readonly property can be initialized once, so use it for values that must not change after construction.Votes: 0GitHub stars: 549
- Php LanguagePut declare(strict_types=1) immediately after the opening PHP tag, before namespaces or other statements: ~~~php <?php declare(strict_types=1); function add(int $left, int $right): int { return $left + $right; } ~~~ Add parameter and return types throughout and use strict === comparisons instead of loose ==.Votes: 0GitHub stars: 549
- Php LanguageUse constructor property promotion to combine declaration, visibility, and assignment: ~~~php final class UserService { public function __construct( private readonly UserRepository $repository, private readonly LoggerInterface $logger, ) { } } ~~~ Keep promoted properties typed and readonly when they represent immutable dependencies.Votes: 0GitHub stars: 549
- Php LanguageUse union types when a value legitimately accepts multiple alternatives, and intersection types when it must satisfy multiple interfaces: ~~~php function formatId(int|string $id): string { return (string) $id; } function consume(Countable&Traversable $items): int { return count($items); } ~~~ Prefer a narrower domain type when possible and add return types to every function.Votes: 0GitHub stars: 549
- Php LanguageUse named arguments when they make optional or reordered parameters clearer: ~~~php $result = paginate( items: $items, page: 2, perPage: 25, ); ~~~ Use the exact parameter names from the function signature and avoid unnecessary naming for obvious positional calls.Votes: 0GitHub stars: 549
- Php SecurityUse PDO prepared statements with bound parameters; never concatenate user input into SQL: ~~~php $statement = $pdo->prepare( 'SELECT * FROM users WHERE id = :id' ); $statement->execute(['id' => $userId]); $user = $statement->fetch(PDO::FETCH_ASSOC); ~~~ Enable exception mode and validate the input before querying. Parameterization protects the SQL structure but does not replace authorization.Votes: 0GitHub stars: 549
- Php SecurityHash passwords with password_hash() using a modern algorithm and verify them with password_verify(): ~~~php $hash = password_hash($password, PASSWORD_ARGON2ID); if (!password_verify($password, $hash)) { throw new AuthenticationException(); } ~~~ Never store plaintext or MD5/SHA-1 password hashes; consider password_needs_rehash() after a successful login.Votes: 0GitHub stars: 549
- Php SecurityEscape user-controlled text at the output context: ~~~php $safeName = htmlentities( $userName, ENT_QUOTES | ENT_HTML5, 'UTF-8', ); echo $safeName; ~~~ Prefer Twig or Blade auto-escaping, use context-appropriate encoding, and never trust raw request values.Votes: 0GitHub stars: 549
- Php SecurityValidate the email before using it: ~~~php $email = filter_var($input, FILTER_VALIDATE_EMAIL); if ($email === false) { throw new InvalidArgumentException('Invalid email address'); } ~~~ Normalize only according to application rules, whitelist allowed values, and still apply authorization and output escaping.Votes: 0GitHub stars: 549
- Php SecurityUse PASSWORD_ARGON2ID with password_hash(): ~~~php $hash = password_hash($password, PASSWORD_ARGON2ID); if ($hash === false) { throw new RuntimeException('Password hashing failed'); } ~~~ Store only the resulting hash, never the password, and use password_verify() for authentication.Votes: 0GitHub stars: 549
- Php SecurityAuthenticate by loading the stored hash and calling password_verify(); never compare plaintext or hashes manually: ~~~php if (!password_verify($password, $user->passwordHash)) { throw new AuthenticationException(); } if (password_needs_rehash($user->passwordHash, PASSWORD_ARGON2ID)) { $user->replacePasswordHash(password_hash($password, PASSWORD_ARGON2ID)); } ~~~ Add rate limiting, secure session handling, and MFA where appropriate, and avoid exposing whether a username or password was wrong.Votes: 0GitHub stars: 549
- Php TestingWrite a focused PHPUnit test through the public service API and mock only an external dependency: ~~~php final class UserServiceTest extends TestCase { public function testFindsUserById(): void { $repository = $this->createMock(UserRepository::class); $user = new User('u-1'); $repository->expects($this->once()) ->method('findById') ->with('u-1') ->willReturn($user); self::assertSame($user, (new UserService($repository))->find('u-1')); } } ~~~ Keep the test independent and repeatable, and use ...Votes: 0GitHub stars: 549
- Php TestingPest provides concise functional syntax while retaining PHPUnit underneath: ~~~php it('finds a user by id', function (): void { $repository = Mockery::mock(UserRepository::class); $repository->expects('findById')->with('u-1')->andReturn(new User('u-1')); expect((new UserService($repository))->find('u-1')->id) ->toBe('u-1'); }); ~~~ Organize tests by Unit, Integration, or Feature, keep them deterministic, and follow red-green-refactor.Votes: 0GitHub stars: 549
- Php TestingMock external boundaries, not private methods or simple data objects: ~~~php $repository = $this->createMock(UserRepository::class); $repository->expects($this->once()) ->method('findById') ->with(42) ->willReturn($user); $service = new UserService($repository); ~~~ Assert public behavior, avoid over-mocking internals, and use an in-memory database or transaction for database integration tests.Votes: 0GitHub stars: 549
- Php TestingUse a data provider to run the same test against multiple independent cases: ~~~php /** * @dataProvider statusProvider */ public function testFormatsStatus(string $status, string $expected): void { self::assertSame($expected, StatusFormatter::format($status)); } public static function statusProvider(): array { return [ 'pending' => ['pending', 'Waiting'], 'paid' => ['paid', 'Complete'], ]; } ~~~ On PHPUnit 10+, prefer the equivalent DataProvider attribute and keep cases descriptive.Votes: 0GitHub stars: 549
- Php TestingPrefer assertSame for exact value and type comparison; use assertEquals only when type coercion is intentionally part of the contract: ~~~php self::assertSame(3, $result); self::assertSame('3', $formatted); ~~~ Also choose focused assertions such as assertCount or assertMatchesRegularExpression where they express behavior clearly.Votes: 0GitHub stars: 549
- Php TestingDo not test private methods directly, over-mock implementation details, or use real network services and production databases in unit tests. Avoid shared mutable fixtures and order-dependent tests. Prefer public interfaces, deterministic fixtures, mocks for external boundaries, and SQLite :memory: or transactions for database tests. Do not chase coverage numbers with meaningless assertions.Votes: 0GitHub stars: 549
- Php ToolingInstall PHPStan as a development dependency and configure a checked source path: ~~~json { "require-dev": { "phpstan/phpstan": "^1.0" } } ~~~ Create phpstan.neon with parameters for src and level 6, and run vendor/bin/phpstan analyse in CI. Keep the dependency locked and review lockfile changes.Votes: 0GitHub stars: 549
- Php ToolingInstall PHP CS Fixer as a development dependency and configure the PSR-12 rule set: ~~~php <?php $config = new PhpCsFixer\Config(); $config->setRules([ '@PSR12' => true, ]); return $config; ~~~ Run the fixer in check mode in CI and keep formatting enforcement separate from static analysis.Votes: 0GitHub stars: 549
- Php ToolingCommit composer.lock for an application so deployments and CI install the reviewed, reproducible dependency graph. Run composer install in CI rather than an unconstrained composer update, use composer audit, and review lockfile diffs before committing them. Do not commit vendor/.Votes: 0GitHub stars: 549
- Php ToolingDeclare PSR-4 mappings in composer.json: ~~~json { "autoload": { "psr-4": { "App\\": "src/" } } } ~~~ Match namespaces and class paths, then run composer dump-autoload. Use Composer's generated autoloader instead of manual require statements.Votes: 0GitHub stars: 549
- Php ToolingKeep Xdebug for local development only. Remove xdebug.so from the production PHP configuration or set XDEBUG_MODE=off in production, then verify the deployed container has no active debugging extension. This avoids debugger overhead and reduces production exposure.Votes: 0GitHub stars: 549
- Php ToolingDefine repeatable Composer scripts for analysis, tests, and the combined check: ~~~json { "scripts": { "analyze": "phpstan analyse", "test": "phpunit", "check": [ "@analyze", "@test" ] } } ~~~ Run them with composer check and execute the same checks in CI.Votes: 0GitHub stars: 549
- Python ArchitectureNo. A Python domain rule should not import `psycopg2` directly; that couples domain policy to the database adapter. Define a repository port in the domain/application layer, inject it into the rule or service, and implement it with a thin `psycopg2` adapter at the edge. Compose the dependency in startup/wiring code. ```python from typing import Protocol class TaskRepository(Protocol): def get_task(self, task_id: str) -> "Task": ... class StatusRule: def __init__(self, tasks: TaskRepository): ...Votes: 0GitHub stars: 549
- Python Architecturefrom typing import Protocol from app.domain.models import ReportFacts class ReportRepository(Protocol): def fetch_facts(self) -> ReportFacts: ... class ReportRenderer(Protocol): def render(self, report: object) -> str: ... class Notifier(Protocol): def send(self, message: str) -> None: ... ``` ```python from app.domain.models import ReportFacts def compute_policy(facts: ReportFacts) -> object: ... ``` ```python from .ports import Notifier, ReportRenderer, ReportRepository from app.domain.poli...Votes: 0GitHub stars: 549
- Python Async RuntimeNo. psycopg2 and subprocess.run are blocking calls and can stall the event loop. Prefer async-native clients; otherwise put each blocking operation behind one explicit asyncio.to_thread boundary, with visible timeout and cancellation behavior.Votes: 0GitHub stars: 549
- Python Async RuntimeVerify cancellation propagation, timeout behavior, cleanup of the watcher and its resources, ownership of long-lived tasks, stop conditions, retry behavior, and the error path. Keep polling-loop control separate from work-item processing and test both cancellation and timeout cases.Votes: 0GitHub stars: 549
- Python Best PracticesSplit the function into focused helpers with an explicit boundary between concerns: validate input, gather data through a persistence collaborator, compute pure policy, render Markdown, and send through a Telegram transport. Pass collaborators in, keep side effects at the edges, and test the helpers and orchestration separately.Votes: 0GitHub stars: 549
- Python Best PracticesRemove god functions that mix orchestration and side effects, hidden globals, boolean soup, duplicated shape cleanup, hidden retries, and print-debugging. Split the function into named, tested helpers with explicit collaborators and visible retry policy.Votes: 0GitHub stars: 549
- Python DatabaseNo. Use parameterized SQL even for internal values, because runtime data can drift or be malformed and f-string SQL creates an injection-prone boundary. Keep the query text fixed and pass values through the driver parameters.Votes: 0GitHub stars: 549
- Python DatabaseOwn the transaction at the service or use-case boundary for the single business action spanning those repository writes. Pass one connection or transaction context into the repositories so they do not commit independently; commit on success and roll back on failure.Votes: 0GitHub stars: 549
- Python Error HandlingA broad exception catch can hide the real exception and turn a verifier failure into an apparently progressing poll. It erases blocker truth, may retry a non-retryable error forever, and can leave inconsistent state. Catch narrow expected exceptions, add context, preserve the exception, and return a structured failure or re-raise unexpected errors.Votes: 0GitHub stars: 549
- Python Error HandlingRestore the mutable state with an explicit rollback before returning. Catch the narrow database exception at the boundary, add operation context without losing the cause, and either re-raise or return a structured failure that identifies the partial mutation and required next action.Votes: 0GitHub stars: 549
- Python LanguagePrefer an explicit contract over a raw dict. Use a frozen dataclass when the result is an immutable value object with behavior or stable attributes; use TypedDict when the boundary is intentionally mapping-shaped or JSON-like. Either gives type checking and documented fields, whereas raw dict leaves the contract implicit.Votes: 0GitHub stars: 549
- Python LanguageUse pathlib.Path for filesystem paths and joins, for example Path(base) / "reports" / name. It is clearer and type-safe for path operations than string concatenation or os.path, while boundary APIs can receive str(path) when needed.Votes: 0GitHub stars: 549
- Python SecurityNo. Interpolating user_input into a shell command with shell=True enables command injection. Use an explicit argument list such as subprocess.run(["git", "show", user_input], shell=False, check=True, ...), validate the allowed revision format, and avoid exposing secrets in errors or logs.Votes: 0GitHub stars: 549
- Python SecurityAudit every tracked requirements surface for dependency drift, run pip-audit and the configured security checks, and verify that the CI gates cover each file and environment. Review secret redaction, input-boundary changes, and the resulting security report rather than accepting a format-only green build.Votes: 0GitHub stars: 549