Giter Site home page Giter Site logo

mezzio / mezzio-session Goto Github PK

View Code? Open in Web Editor NEW
19.0 19.0 13.0 725 KB

Session container and middleware for PSR-7 applications

Home Page: https://docs.mezzio.dev/mezzio-session/

License: BSD 3-Clause "New" or "Revised" License

PHP 100.00%
hacktoberfest

mezzio-session's Introduction

mezzio

Build Status Type Coverage

Develop PSR-7 middleware applications in minutes!

mezzio builds on laminas-stratigility to provide a minimalist PSR-7 middleware framework for PHP, with the following features:

Installation

We provide two ways to install Mezzio, both using Composer: via our skeleton project and installer, or manually.

Using the skeleton + installer

The simplest way to install and get started is using the skeleton project, which includes installer scripts for choosing a router, dependency injection container, and optionally a template renderer and/or error handler. The skeleton also provides configuration for officially supported dependencies.

To use the skeleton, use Composer's create-project command:

composer create-project mezzio/mezzio-skeleton <project dir>

This will prompt you through choosing your dependencies, and then create and install the project in the <project dir> (omitting the <project dir> will create and install in a mezzio-skeleton/ directory).

Manual Composer installation

You can install Mezzio standalone using Composer:

composer require mezzio/mezzio

However, at this point, Mezzio is not usable, as you need to supply minimally:

  • a router.
  • a dependency injection container.

We currently support and provide the following routing integrations:

We recommend using a dependency injection container, and typehint against PSR-11 Container. We can recommend the following implementations:

  • laminas-servicemanager: composer require laminas/laminas-servicemanager
  • Pimple (see docs for more details): composer require laminas/laminas-pimple-config
  • Aura.Di (see docs for more details): composer require laminas/laminas-auradi-config

Additionally, you may optionally want to install a template renderer implementation, and/or an error handling integration. These are covered in the documentation.

Documentation

Documentation is in the doc tree, and can be compiled using mkdocs:

mkdocs build

Additionally, public-facing, browseable documentation is available at https://docs.mezzio.dev/mezzio/

mezzio-session's People

Contributors

boesing avatar dependabot[bot] avatar froschdesign avatar geerteltink avatar ghostwriter avatar gsteel avatar hannesvdvreken avatar harikt avatar kynx avatar laminas-bot avatar michaelgooden avatar michalbundyra avatar ocramius avatar pine3ree avatar renovate[bot] avatar samsonasik avatar thexpand avatar weierophinney avatar xerkus avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mezzio-session's Issues

mezzio-session-ext vs php-ext-session

Feature Request

Q A
New Features yes
BC Break maybe

Summary

This is more a comparison of behavior of mezzio-session-ext implementation vs the php ext-session.

  1. calling session_start() via php-ext-session always sets a session-cookie in the first session-aware script's response even if no data is actually stored in the session. mezzio-session-ext only sets a response session-cookie if the session-data is changed or the session is regenerated. see (*)

  2. php-ext-session sets the session-cookie in the response only if the session-id is changed either when the session is fresh (new) or its id is regenerated. mezzio-session-ext always sets the response session cookie if the session-data has been altered even if the session-id is unchanged. see (*)

  3. php-ext-session always sends cache-limiters headers after a session_start() call. mezzio-session-ext only sends cache-limiters headers when the session-data ( or the session is regenerated) has been changed (*)

  4. after calling session_start()(or session_regenerate_id()) the actual session id is available right away and may be used programmatically to identify the client browser session in the first fresh-session-generating script execution. With mezzio-session-ext in a fresh session or a regenerated session context the actual/final session-id is only available inside PhpSessionPersistence::persistSession() . see (**)

  5. feature/maybe BC: php-ext-session does not set a new session-cookie (with same id) if we only change the session-cookie-lifetime. It would be useful to make mezzio-session-ext always send a new cooki when the session-lifetime is changed ($session->persistSessionFor()). This could be achieved allowing null to be returned in SessionCookiePersistenceInterface::getSessionLifetime(). A null value could be used to indicate that the cookie-lifetime has not been changed, any unsigned int to programmatically set the cookie-lifetime, 0 for restoring to a session-cookie.

  6. BC renaming of SessionCookiePersistenceInterface methods
    we now have:

  • SessionIdentifierAwareInterface::getID()
  • SessionCookiePersistenceInterface::persistSessionFor(int $duration)
  • SessionCookiePersistenceInterface::getSessionLifetime()

In my opinion we should have for consistency:

  • SessionCookiePersistenceInterface::persistFor(int $duration)
  • SessionCookiePersistenceInterface::getLifetime()

so that we can make calls call $session->getLifetime() and $session->persistFor(86400). The word 'Session' in the method seems redundant to me, same as $session->getSessionID() would seem.

(*) behaviours 1 and 2 (and 3) could be achieved in PhpSessionPersistence::persistSession() by comparing the initial session-id (from the request) with the final value and by calling PhpSessionPersistence::regenerateSession() even if only $id === '' or by triggering a $session = $session->regenerate() when $id === '' and then checking $session->isRegenerated().

(**) behavior 3 could be achieved partially using a new SessionIsNewAwareInterface featuring an isNew() method. The new session id would be generated and set in the session instace along with a $isNew constructor param. But I haven not find a way to get the final id from the session instance after a regenerate() call in the inner handler. A SessionIsNewAwareInterface is the solution I have been adopted in my code, to both achieve fresh data-less session and session-id availability inside my handlers code. About that, php session books states that:

  • Session support in PHP consists of a way to preserve certain data across subsequent accesses.
  • A visitor accessing your web site is assigned a unique id, the so-called session id. (...)
  • The session support allows you to store data between requests...

So php-ext-session always assigns a unique id and allows you to store data. I interpret this as 'data-less' an only 'client-identifying' session behavior

kind regards

PHP 8.0 support

Feature Request

Q A
New Feature yes

Summary

To be prepared for the december release of PHP 8.0, this repository has some additional TODOs to be tested against the new major version.

In order to make this repository compatible, one has to follow these steps:

  • Modify composer.json to provide support for PHP 8.0 by adding the constraint ~8.0.0
  • Modify composer.json to drop support for PHP less than 7.3
  • Modify composer.json to implement phpunit 9.3 which supports PHP 7.3+
  • Modify .travis.yml to ignore platform requirements when installing composer dependencies (simply add --ignore-platform-reqs to COMPOSER_ARGS env variable)
  • Modify .travis.yml to add PHP 8.0 to the matrix (NOTE: Do not allow failures as PHP 8.0 has a feature freeze since 2020-08-04!)
  • Modify source code in case there are incompatibilities with PHP 8.0

Hi there! I have a similar library.

Hey. I have followed you on Github and, today, I noticed that you were working on this repo.
I had worked on somewhat similar library a few months back. It's called ps7-session.

It is not completely dependent on expressive. It's a php7 based session library with added support for interop middleware-based applications. Check this

I was wondering if we could talk about whether these two could complement each other. If using that library as a dependency is a good idea. I am open to moving it to zend organization if it's good enough for you people :D
Or, maybe, this library can take some ideas from my library.

The reason I created that library because I was trying to run an expressive based application with reactphp/http and $_SESSION was not usable. Running the expressive application with reactphp was actually experimental and won't make it to production(atleast for now). But, on the process, I was motivated enough to write that library.

Best Regards,
Your long-time fan and follower,
Ujjwal Ojha


Originally posted by @ojhaujjwal at zendframework/zend-expressive-session#1

avoid code duplication in persistence impl.

Feature Request

Q A
New Feature yes (refactoring)
RFC no
BC Break no

Summary

Hello, having implemented the cache-limiter generation feature in mezzio-session-ext, I found out that the same code is duplicated in mezzio-session-cache.
This is because php-session is one extension that generates a response cookie and cache-header always in the same way (with custom params) and allowing us to attach different save-handlers, while mezzio-session persistence layer is more generic and takes care both of the persistence of the session-data and the session-identification in the client-browser. mezzio-session does not assume that phpsession-like headers must be used in all persistence implementations.

Some of these implementations may have common codebase.
IMO it would be better to have either traits for such common features or cache-headers-generator/set-cookie-header-generator services as dependencies for the persistence implementations that require them.

kind regards

Deprecate Session as a Request attribute in favor of dedicated Helper

Feature Request

Q A
New Feature yes
RFC yes
BC Break no

Hi, currently the Session instance is set as an attribute of the Request:

$response = $handler->handle($request->withAttribute(self::SESSION_ATTRIBUTE, $session));

In my humble opinion this is an anti-pattern:

  1. Session has nothing to do with the pure concept of a Request; it leverages the Cookie functionalities, but it's not stritcly coupled to the Request itself
  2. As an attribute, is basically injected everywhere, even to following Middlewares and Handlers that don't need it and shouldn't be aware of it
  3. It breaks typing (and that's a smell by itself): every Request attributes derives from a HTTP Request so theoretically only scalar types are allowed; Session instead needs a non-scalar type but cannot be enforced by the PSR-7 specifications

What I propose here is the same approach used by Mezzio Helpers like ServerUrlMiddleware: a dedicated SessionHelper is filled and the Request untouched; if a class needs the Session, its factory must inject the SessionHelper to it, otherwise the Session is unreachable.

The same issue affects other components (see AuthenticationMiddleware.php) but Session seems to me the first one to start topic with.

Ping @Ocramius for https://twitter.com/Ocramius/status/1244964513578876928

Allow dflydev/fig-cookies v3.0

Bug Report

Q A
Version(s) >= 1.4.0

Summary

Installation on PHP 8 is broken due to external dependency

dflydev/fig-cookies released the PHP 8 support as a new major version for whatever reason. I see no other API or requirement changes there. The tests seem to pass too

Session destroy

I see that SessionInterface does not provide the ability to session destroy .

I am writing my session handler that works with the database.

I created my middleware, which is called before zend-expressive-session-ext and zend-expressive-session:

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $sessionHandler = new DatabaseSessionHandler($this->pdo);
        session_set_save_handler($sessionHandler, true);

        return $handler->handle($request);
    }

It all works, the difference is not noticeable.
But I had a problem with logout.

    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        /** @var LazySession $session */
        $session = $request->getAttribute(SessionMiddleware::SESSION_ATTRIBUTE);

        $session->clear(); // does not destroy the session (only clearing data)

        return new RedirectResponse($this->urlHelper->generate('home'), ResponseInfo::HTTP_FOUND);
    }

Solution to the problem:

    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        /** @var LazySession $session */
        $session = $request->getAttribute(SessionMiddleware::SESSION_ATTRIBUTE);

        $session->clear(); // does not destroy the session (only clearing data)
        session_destroy(); // everything works however we don't use SessionInterface

        return new RedirectResponse($this->urlHelper->generate('home'), ResponseInfo::HTTP_FOUND);
    }

So, why the SessionInterface doesn't have a destroy method? I think this can be a problem in some cases.


Originally posted by @nepster-web at zendframework/zend-expressive-session#29

Remove session set value will convert to an array/obj value.

I saw the Session::extractSerializableValue method comment

This value should be used by set() operations to ensure that the values
within a session are serializable across any session adapter.

But most of adapters can store string after using serialize() function . And I think this is adapter layer.

And then, I think can remove it.

Code to reproduce the issue

class User extends \ArrayObject {
}

$session->set(User::class, new User(['id' => 1]))
$user = $session->get(User::class); 

Expected results

$user instanceof User; 

Actual results

$user; 
// Is array:
// ['id' => 1]

Originally posted by @Moln at zendframework/zend-expressive-session#37

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Repository problems

These problems occurred while renovating this repository. View logs.

  • WARN: Use matchDepNames instead of matchPackageNames

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

composer
composer.json
  • php ~8.1.0 || ~8.2.0 || ~8.3.0
  • dflydev/fig-cookies ^3.0
  • psr/container ^1.0 || ^2.0
  • psr/http-server-middleware ^1.0
  • laminas/laminas-coding-standard ~2.5.0
  • laminas/laminas-diactoros ^3.3.0
  • phpunit/phpunit ^10.5.10
  • psalm/plugin-phpunit ^0.18.4
  • vimeo/psalm ^5.21.1
github-actions
.github/workflows/continuous-integration.yml
.github/workflows/docs-build.yml
.github/workflows/release-on-milestone-closed.yml

  • Check this box to trigger a request for Renovate to run again on this repository

Psalm integration

Feature Request

Q A
QA yes

Summary

As decided during the Technical-Steering-Committee Meeting on August 3rd, 2020, Laminas wants to implement vimeo/psalm in all packages.

Implementing psalm is quite easy.

Required

  • Create a psalm.xml in the project root
  • Copy and paste the contents from this psalm.xml.dist
  • Run $ composer require --dev vimeo/psalm
  • Run $ vendor/bin/psalm --set-baseline=psalm-baseline.xml
  • Add a composer script static-analysis with the command psalm --shepherd --stats
  • Add a new line to script: in .travis.yml: - if [[ $TEST_COVERAGE == 'true' ]]; then composer static-analysis ; fi
  • Remove phpstan from the project (phpstan.neon.dist, .travis.yml entry, composer.json require-dev and scripts)
Optional
  • Fix as many psalm errors as possible.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.