안녕하세요 여러분!
반복되는 데이터베이스 쿼리로 인해 애플리케이션 실행 속도가 느려지나요? 아니면 서로 다른 캐싱 라이브러리 간에 전환하는 데 문제가 있습니까? PHP의 캐싱을 예측 가능하고 상호 교환 가능하게 만드는 표준인 PSR-6에 대해 살펴보겠습니다!
이 기사는 PHP PSR 표준 시리즈의 일부입니다. 처음이라면 PSR-1 기본부터 시작하는 것이 좋습니다.
PSR-6은 어떤 문제를 해결하나요? (2분)
PSR-6 이전에는 각 캐시 라이브러리에 고유한 작업 방식이 있었습니다. Memcached에서 Redis로 전환하고 싶으신가요? 코드를 다시 작성하세요. 한 프레임워크에서 다른 프레임워크로 마이그레이션하시나요? 새로운 캐싱 API에 대해 알아보세요. PSR-6은 모든 캐시 라이브러리가 구현할 수 있는 공통 인터페이스를 제공하여 이 문제를 해결합니다.
핵심 인터페이스(5분)
두 명의 주요 플레이어를 살펴보겠습니다.
1. CacheItemPoolInterface
캐시 관리자입니다. 물건을 보관하고 회수할 수 있는 창고라고 생각하세요.
<?php namespace Psr\Cache; interface CacheItemPoolInterface { public function getItem($key); public function getItems(array $keys = array()); public function hasItem($key); public function clear(); public function deleteItem($key); public function deleteItems(array $keys); public function save(CacheItemInterface $item); public function saveDeferred(CacheItemInterface $item); public function commit(); } ?>
2. CacheItemInterface
이는 캐시에 있는 단일 항목을 나타냅니다.
<?php namespace Psr\Cache; interface CacheItemInterface { public function getKey(); public function get(); public function isHit(); public function set($value); public function expiresAt($expiration); public function expiresAfter($time); } ?>
실습(10분)
다음은 코드 베이스의 실제 예입니다.
1. 캐시 아이템 구현
<?php namespace JonesRussell\PhpFigGuide\PSR6; use Psr\Cache\CacheItemInterface; use DateTimeInterface; use DateInterval; use DateTime; class CacheItem implements CacheItemInterface { private $key; private $value; private $isHit; private $expiration; public function __construct(string $key) { $this->key = $key; $this->isHit = false; } public function getKey(): string { return $this->key; } public function get() { return $this->value; } public function isHit(): bool { return $this->isHit; } public function set($value): self { $this->value = $value; return $this; } public function expiresAt(?DateTimeInterface $expiration): self { $this->expiration = $expiration; return $this; } public function expiresAfter($time): self { if ($time instanceof DateInterval) { $this->expiration = (new DateTime())->add($time); } elseif (is_int($time)) { $this->expiration = (new DateTime())->add(new DateInterval("PT{$time}S")); } else { $this->expiration = null; } return $this; } // Helper method for our implementation public function getExpiration(): ?DateTimeInterface { return $this->expiration; } // Helper method for our implementation public function setIsHit(bool $hit): void { $this->isHit = $hit; } }
2. 캐시 풀 구현
<?php namespace JonesRussell\PhpFigGuide\PSR6; use Psr\Cache\CacheItemPoolInterface; use Psr\Cache\CacheItemInterface; use RuntimeException; class FileCachePool implements CacheItemPoolInterface { private $directory; private $deferred = []; public function __construct(string $directory) { if (!is_dir($directory) && !mkdir($directory, 0777, true)) { throw new RuntimeException("Cannot create cache directory: {$directory}"); } $this->directory = $directory; } public function getItem($key): CacheItemInterface { $this->validateKey($key); if (isset($this->deferred[$key])) { return $this->deferred[$key]; } $item = new CacheItem($key); $path = $this->getPath($key); if (file_exists($path)) { try { $data = unserialize(file_get_contents($path)); if (!$data['expiration'] || $data['expiration'] > new DateTime()) { $item->set($data['value']); $item->setIsHit(true); return $item; } unlink($path); } catch (\Exception $e) { // Log error and continue with cache miss } } return $item; } public function getItems(array $keys = []): iterable { $items = []; foreach ($keys as $key) { $items[$key] = $this->getItem($key); } return $items; } public function hasItem($key): bool { return $this->getItem($key)->isHit(); } public function clear(): bool { $this->deferred = []; $files = glob($this->directory . '/*.cache'); if ($files === false) { return false; } $success = true; foreach ($files as $file) { if (!unlink($file)) { $success = false; } } return $success; } public function deleteItem($key): bool { $this->validateKey($key); unset($this->deferred[$key]); $path = $this->getPath($key); if (file_exists($path)) { return unlink($path); } return true; } public function deleteItems(array $keys): bool { $success = true; foreach ($keys as $key) { if (!$this->deleteItem($key)) { $success = false; } } return $success; } public function save(CacheItemInterface $item): bool { $path = $this->getPath($item->getKey()); $data = [ 'value' => $item->get(), 'expiration' => $item->getExpiration() ]; try { if (file_put_contents($path, serialize($data)) === false) { return false; } return true; } catch (\Exception $e) { return false; } } public function saveDeferred(CacheItemInterface $item): bool { $this->deferred[$item->getKey()] = $item; return true; } public function commit(): bool { $success = true; foreach ($this->deferred as $item) { if (!$this->save($item)) { $success = false; } } $this->deferred = []; return $success; } private function getPath(string $key): string { return $this->directory . '/' . sha1($key) . '.cache'; } private function validateKey(string $key): void { if (!is_string($key) || preg_match('#[{}()/@:\\]#', $key)) { throw new InvalidArgumentException( 'Invalid key: ' . var_export($key, true) ); } } }
실습(5분)
실제 코드에서 어떻게 사용하는지 살펴보겠습니다.
// 基本用法 $pool = new FileCachePool('/path/to/cache'); try { // 存储值 $item = $pool->getItem('user.1'); if (!$item->isHit()) { $userData = $database->fetchUser(1); // 您的数据库调用 $item->set($userData) ->expiresAfter(3600); // 1 小时 $pool->save($item); } $user = $item->get(); } catch (\Exception $e) { // 优雅地处理错误 log_error('缓存操作失败:' . $e->getMessage()); $user = $database->fetchUser(1); // 回退到数据库 }
공통의 함정(3분)
- 키 확인
- 오류 처리
다음은 무엇입니까?
내일은 PSR-7(HTTP 메시지 인터페이스)에 대해 논의하겠습니다. 더 간단한 캐싱에 관심이 있다면 PSR-6에 대한 더 간단한 대안을 제공하는 다가오는 PSR-16(Simple Caching) 기사를 계속 지켜봐 주시기 바랍니다.
리소스
- PSR-6 공식 사양
- 샘플 코드베이스(v0.6.0 - PSR-6 구현)
- Symfony 캐싱 구성요소
- PHP 캐시
위 내용은 PHP의 PSR 캐싱 인터페이스의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

데이터베이스 스토리지 세션 사용의 주요 장점에는 지속성, 확장 성 및 보안이 포함됩니다. 1. 지속성 : 서버가 다시 시작 되더라도 세션 데이터는 변경되지 않아도됩니다. 2. 확장 성 : 분산 시스템에 적용하여 세션 데이터가 여러 서버간에 동기화되도록합니다. 3. 보안 : 데이터베이스는 민감한 정보를 보호하기 위해 암호화 된 스토리지를 제공합니다.

SessionHandlerInterface 인터페이스를 구현하여 PHP에서 사용자 정의 세션 처리 구현을 수행 할 수 있습니다. 특정 단계에는 다음이 포함됩니다. 1) CustomsessionHandler와 같은 SessionHandlerInterface를 구현하는 클래스 만들기; 2) 인터페이스의 방법 (예 : Open, Close, Read, Write, Despare, GC)의 수명주기 및 세션 데이터의 저장 방법을 정의하기 위해 방법을 다시 작성합니다. 3) PHP 스크립트에 사용자 정의 세션 프로세서를 등록하고 세션을 시작하십시오. 이를 통해 MySQL 및 Redis와 같은 미디어에 데이터를 저장하여 성능, 보안 및 확장 성을 향상시킬 수 있습니다.

SessionId는 웹 애플리케이션에 사용되는 메커니즘으로 사용자 세션 상태를 추적합니다. 1. 사용자와 서버 간의 여러 상호 작용 중에 사용자의 신원 정보를 유지하는 데 사용되는 무작위로 생성 된 문자열입니다. 2. 서버는 쿠키 또는 URL 매개 변수를 통해 클라이언트로 생성하여 보낸다. 3. 생성은 일반적으로 임의의 알고리즘을 사용하여 독창성과 예측 불가능 성을 보장합니다. 4. 실제 개발에서 Redis와 같은 메모리 내 데이터베이스를 사용하여 세션 데이터를 저장하여 성능 및 보안을 향상시킬 수 있습니다.

JWT 또는 쿠키를 사용하여 API와 같은 무국적 환경에서 세션을 관리 할 수 있습니다. 1. JWT는 무국적자 및 확장 성에 적합하지만 빅 데이터와 관련하여 크기가 크다. 2. 쿠키는보다 전통적이고 구현하기 쉽지만 보안을 보장하기 위해주의해서 구성해야합니다.

세션 관련 XSS 공격으로부터 응용 프로그램을 보호하려면 다음 조치가 필요합니다. 1. 세션 쿠키를 보호하기 위해 Httponly 및 Secure 플래그를 설정하십시오. 2. 모든 사용자 입력에 대한 내보내기 코드. 3. 스크립트 소스를 제한하기 위해 컨텐츠 보안 정책 (CSP)을 구현하십시오. 이러한 정책을 통해 세션 관련 XSS 공격을 효과적으로 보호 할 수 있으며 사용자 데이터가 보장 될 수 있습니다.

PHP 세션 성능을 최적화하는 방법 : 1. 지연 세션 시작, 2. 데이터베이스를 사용하여 세션을 저장, 3. 세션 데이터 압축, 4. 세션 수명주기 관리 및 5. 세션 공유 구현. 이러한 전략은 높은 동시성 환경에서 응용의 효율성을 크게 향상시킬 수 있습니다.

THESESSION.GC_MAXLIFETIMESETTINGINSTTINGTINGSTINGTERMINESTERMINESTERSTINGSESSIONDATA, SETINSECONDS.1) IT'SCONFIGUDEDINPHP.INIORVIAINI_SET ()

PHP에서는 Session_Name () 함수를 사용하여 세션 이름을 구성 할 수 있습니다. 특정 단계는 다음과 같습니다. 1. Session_Name () 함수를 사용하여 Session_Name ( "my_session")과 같은 세션 이름을 설정하십시오. 2. 세션 이름을 설정 한 후 세션을 시작하여 세션을 시작하십시오. 세션 이름을 구성하면 여러 응용 프로그램 간의 세션 데이터 충돌을 피하고 보안을 향상시킬 수 있지만 세션 이름의 독창성, 보안, 길이 및 설정 타이밍에주의를 기울일 수 있습니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

mPDF
mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

VSCode Windows 64비트 다운로드
Microsoft에서 출시한 강력한 무료 IDE 편집기

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

PhpStorm 맥 버전
최신(2018.2.1) 전문 PHP 통합 개발 도구

ZendStudio 13.5.1 맥
강력한 PHP 통합 개발 환경
