From d61366242d35c6197905a1c6fdec8025bf1b238d Mon Sep 17 00:00:00 2001 From: mychidarko Date: Fri, 7 Jul 2023 02:22:55 +0000 Subject: [PATCH 1/4] feat: add schema docs --- .vitepress/config.ts | 1 + src/docs/mvc/migrations.md | 4 + src/docs/mvc/schema.md | 262 +++++++++++++++++++++++++++++++++++++ 3 files changed, 267 insertions(+) create mode 100644 src/docs/mvc/schema.md diff --git a/.vitepress/config.ts b/.vitepress/config.ts index 5803bec1..60841558 100644 --- a/.vitepress/config.ts +++ b/.vitepress/config.ts @@ -314,6 +314,7 @@ const mainSidebar = [ { text: 'Views', link: '/docs/mvc/views' }, { text: 'Models', link: '/docs/mvc/models' }, { text: 'Migrations', link: '/docs/mvc/migrations' }, + { text: 'Schema', link: '/docs/mvc/schema' }, { text: 'Seeders', link: '/docs/mvc/seeds' }, { text: 'Factories', link: '/modules/mvc-core/factories' }, // { text: 'MVC Console Tool', link: '/docs/mvc/console' }, diff --git a/src/docs/mvc/migrations.md b/src/docs/mvc/migrations.md index fa356682..9c2e85e7 100644 --- a/src/docs/mvc/migrations.md +++ b/src/docs/mvc/migrations.md @@ -67,6 +67,10 @@ class CreateUsers extends Database { } ``` +::: tip Note +Instead of building your migrations from scratch, you can use Leaf's schema builder to generate migrations from JSON data. [Learn more](/docs/mvc/schema). +::: + ## Running migrations To run all of your outstanding migrations, execute the `db:migrate` command: diff --git a/src/docs/mvc/schema.md b/src/docs/mvc/schema.md new file mode 100644 index 00000000..89a95eac --- /dev/null +++ b/src/docs/mvc/schema.md @@ -0,0 +1,262 @@ +# Schema + + + +Schema is a simple, yet powerful tool for generating database migrations from JSON data. Instead of dealing with the stress of writing your database migrations from scratch and thinking about all the types of your data, you can simply create a JSON file with sample data and let Leaf do the rest. + +**DB Schema is only available in Leaf MVC and Leaf API.** + +## Writing your schema + +Schema can be found in the `app/database/schema` folder. To get started, create a new JSON file in the the schemas directory. You can name it anything you want, but it's best to name it after the table you're creating as that is what Leaf will expect unless you specify otherwise. + +We can start off by creating a `users.json` file. All that this file should contain is an example of what your data should look like. For example: + +```json +{ + "id": 1, + "username?": "username", + "name": "Full Name", + "created_at": "", + "updated_at": "" +} +``` + +## Using your schema + +To use your schema, you can call `Leaf\Schema::build` in your migration. It takes in the name of the schema file to build your migrations with. + +```php{12} +... +use Leaf\Schema; + +class CreateUsers extends Database { + /** + * Run the migrations. + * + * @return void + */ + public function up() + { + Schema::build("users"); + } + + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + $this->capsule::schema()->dropIfExists("users"); + } +} +``` + +In the example above, the `users` schema will be used to generate the migration. This means that the `users` table will be created in your database with the fields specified in the schema. To actually run the migration, you can use the `db:migrate` command. + +```bash +php leaf db:migrate +``` + +Read more about [migrations](/docs/mvc/migrations). + +## Data Types + +Leaf Schema is flexible and allows you to specify the type of data you want to store in your database. For the most part, Leaf Schema will automatically detect the type of data you want to store, but you can also specify the type of data you want to store. + +### Automatic Types + +Leaf Schema will automatically detect the type of data you want to store in your database. For example, if you want to store a string in your database, you can simply specify the string in your schema. + +```json +{ + ... + "username": "username" +} +``` + +In the example above, the `username` field will be set to `$table->string` in the migration. This is the same as using `$table->string('username')` in your migration. + +Automatic types are supported for the following types of data: + +- string +- integer +- boolean +- float +- array (will be converted to `enum` in the migration) +- json (should be a stringified json object) + +### Manually Adding Types + +Leaf Schema supports all the types supported by Laravel's Schema Builder. You can specify the type of data you want to store in your database by using the type as the value of the field. + +```json +{ + ... + "username:text": "username" +} +``` + +In the example above, the `username` field will be set to `$table->text` in the migration. This is the same as using `$table->text('username')` in your migration. + +
+bigIncrements +bigInteger +binary +boolean +char +dateTimeTz +dateTime +date +decimal +double +enum +float +foreignId +foreignIdFor +foreignUlid +foreignUuid +geometryCollection +geometry +id +increments +integer +ipAddress +json +jsonb +lineString +longText +macAddress +mediumIncrements +mediumInteger +mediumText +morphs +multiLineString +multiPoint +multiPolygon +nullableMorphs +nullableTimestamps +nullableUlidMorphs +nullableUuidMorphs +point +polygon +rememberToken +set +smallIncrements +smallInteger +softDeletesTz +softDeletes +string +text +timeTz +time +timestampTz +timestamp +timestampsTz +timestamps +tinyIncrements +tinyInteger +tinyText +unsignedBigInteger +unsignedDecimal +unsignedInteger +unsignedMediumInteger +unsignedSmallInteger +unsignedTinyInteger +ulidMorphs +uuidMorphs +ulid +uuid +year +
+ +## Nullable Fields + +If you want to specify that a field should be nullable, you can use the `?` symbol after the field name. This is the same as using `$table->nullable()` in your migration. + +```json +{ + ... + "username?": "username" +} +``` + +### Nullable + Types + +If you want to specify that a field should be nullable and also specify the type of data you want to store, you can use the `?` symbol after the field name and also specify the type of data you want to store after the `?` symbol, using `:`. + +```json +{ + ... + "username?:string": "username" +} +``` + +## `id` + +The `id` type is used to specify that the field is an auto-incrementing primary key. This is the same as using `$table->bigIncrements('id')` in your migration. Setting a field to `id` will automatically set the field to be an auto-incrementing primary key. + +```json +{ + "id": 1, + ... +} +``` + +If you want to set a field to be an auto-incrementing primary key, but you don't want to set the field to `id`, you can use the `id` type in the key of the field using `:`. + +```json +{ + "user_id : id": 1, + ... +} +``` + +In the example above, the `user_id` field will be set to `$table->bigIncrements` in the migration. This is the same as using `$table->bigIncrements('user_id')` in your migration. Just as with the `id` type, Leaf Schema allows you to specify the name of the field with the type using `:`. + +**The spaces around the `:` are optional, so you can also use `user_id:id`.** + +## `timestamps` + +The `timestamps` type is used to specify that the table should have `created_at` and `updated_at` fields. This is the same as using `$table->timestamps()` in your migration. + +```json +{ + ... + "timestamps": "" +} +``` + +## Foreign Keys + +The `*` type is used to specify that the field should be a foreign key. This is the same as using `$table->foreignId` in your migration. + +```json +{ + ... + "user_id*": 1 +} +``` + +## Soft Deletes + +To specify that a table should have soft deletes, you can use the `softDeletes` key. This is the same as using `$table->softDeletes()` in your migration. + +```json +{ +... +"softDeletes": "" +} +``` + +## Remember Tokens + +To specify that a table should have a remember token, you can use the `rememberToken` key. This is the same as using `$table->rememberToken()` in your migration. + +```json +{ + ... + "rememberToken": "" +} +``` From aacabe388ce35663816f1ce0a13e73fa5f7c985d Mon Sep 17 00:00:00 2001 From: mychidarko Date: Fri, 7 Jul 2023 02:33:59 +0000 Subject: [PATCH 2/4] feat: update grid list --- .vitepress/theme/styles/pages.css | 6 ++++++ src/docs/mvc/schema.md | 2 +- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/.vitepress/theme/styles/pages.css b/.vitepress/theme/styles/pages.css index 4721cec9..d859a439 100644 --- a/.vitepress/theme/styles/pages.css +++ b/.vitepress/theme/styles/pages.css @@ -13,3 +13,9 @@ .vt-doc.sponsor h3 .header-anchor { display: none; } + +.vt-grid-list { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); + grid-gap: 1rem; +} diff --git a/src/docs/mvc/schema.md b/src/docs/mvc/schema.md index 89a95eac..2cd31abb 100644 --- a/src/docs/mvc/schema.md +++ b/src/docs/mvc/schema.md @@ -100,7 +100,7 @@ Leaf Schema supports all the types supported by Laravel's Schema Builder. You ca In the example above, the `username` field will be set to `$table->text` in the migration. This is the same as using `$table->text('username')` in your migration. -
+
bigIncrements bigInteger binary From a949c5d8f7b0a38d3f2f860c1cf29a89b4ea6967 Mon Sep 17 00:00:00 2001 From: mychidarko Date: Sat, 8 Jul 2023 21:38:51 +0000 Subject: [PATCH 3/4] feat: update session flash docs --- src/modules/session/flash.md | 128 +++++------ src/modules/session/index.md | 421 ++++++++++++++++++++--------------- 2 files changed, 305 insertions(+), 244 deletions(-) diff --git a/src/modules/session/flash.md b/src/modules/session/flash.md index d39728ba..7030baab 100755 --- a/src/modules/session/flash.md +++ b/src/modules/session/flash.md @@ -1,27 +1,19 @@ # Leaf Flash -::: warning Watch out -Leaf flash is a class available on the leaf session module. Check out the [session module docs](/modules/session/) for installation instructions. -::: +Session flash messages are temporary messages that are stored in the session and displayed to the user for a short duration, usually just until they are shown once. These messages are commonly used to provide feedback or notifications to the user after a specific action or event, such as successfully completing a form submission, encountering an error, or performing a specific operation. -This is a simple helper for creating and managing PHP flash messages. It is highly customizable just like the rest of Leaf and fits right into any project no matter it's size or scope. - -To get started, simply call the method you want to use. Leaf Flash uses static methods, so there's no need for initializing. - -**Flash uses session to temporarily save variables.** +Leaf session provides a simple interface for creating and managing flash messages. Flash messages are stored in the session and can be retrieved and displayed in the view. ## Config -As mentioned above, Leaf Flash is super customizable. All this customization is done through Leaf Flash config. +Leaf Flash comes with a default configuration that works out of the box. However, you can change the configuration to suit your needs. You can skip this section if you're using the default configuration. -**You don't need to do any of this. Leaf Flash works perfectly out of the box.** +Using the `config()` method, you can change where Leaf stores flash messages in session, the keys for messages and saved content. The available options are: -Using the config method, you can change where Leaf stores flash messages in session, the keys for messages and saved content. The available options are: - -- key: The key to save flash array in session. Default: leaf.flash, -- default: The key for default flash messages. Default: message, -- saved: The key for saved flash messages. Default: leaf.flash.saved, +- key: The key to save flash array in session. Default: `leaf.flash`, +- default: The key for default flash messages. Default: `message`, +- saved: The key for saved flash messages. Default: `leaf.flash.saved`,
@@ -56,133 +48,133 @@ Flash::set("This is my message"); **Flash searches for an existing session and creates one if there's no active session.** -## set - -Set as the name implies allows you to save a flash message. - -
- -```php -flash()->set("This is my message"); -``` +## Adding a new flash -
-
+Leaf Flash provides a `set()` method for adding new flash messages to the session. The `set()` method accepts two arguments: -```php -Leaf\Flash::set("This is my message"); -``` - -
- -This saves the message with the key `message`. If you want to use another key, you can pass it in as a second parameter. +- The item to flash +- The key to save it under. The key is optional and defaults to `message`.
```php -flash()->set("This is my message", "info"); +flash()->set('This is my message'); +flash()->set('This is my message', 'info'); + +// accepts different types of data +flash()->set($userObject); +flash()->set($userArray); +flash()->set($userString); +flash()->set($userInt); ```
```php -Leaf\Flash::set("This is my message", "info"); +Leaf\Flash::set('This is my message'); +Leaf\Flash::set('This is my message', 'info'); + +// accepts different types of data +Leaf\Flash::set($userObject); +Leaf\Flash::set($userArray); +Leaf\Flash::set($userString); +Leaf\Flash::set($userInt); ```
-Using this functionality you can have multiple flash messages at the same time. In that case, they won't be unset until they are viewed. +Leaf flash allows you to keep multiple flash messages at the same time. They won't be removed until you show them. To do this, you will need to set different keys for each flash message.
```php -flash()->set("This is my message", "info"); -flash()->set("This is my message", "error"); -flash()->set("This is my message", "success"); +flash()->set('This is my message', 'info'); +flash()->set('This is my message', 'error'); +flash()->set('This is my message', 'success'); ```
```php -Leaf\Flash::set("This is my message", "info"); -Leaf\Flash::set("This is my message", "error"); -Leaf\Flash::set("This is my message", "success"); +Leaf\Flash::set('This is my message', 'info'); +Leaf\Flash::set('This is my message', 'error'); +Leaf\Flash::set('This is my message', 'success'); ```
-## unset +## Displaying a flash message -`unset` does the opposite: it removes a flash message. You won't be needing this method in most cases. +Leaf Flash provides a `display()` method that you can use to retrieve your session flash. As soon as the flash message is retrieved, it is removed from the session which means it won't show on the next load.
```php -flash()->unset("This is my message"); -flash()->unset("This is my message", "info"); +flash()->set('message 1'); +flash()->set('message 2', 'info'); + +echo flash()->display(); // message 1 +echo flash()->display('info'); // message 2 ```
```php -Leaf\Flash::unset("This is my message"); -Leaf\Flash::unset("This is my message", "info"); +Leaf\Flash::set('message 1'); +Leaf\Flash::set('message 2', 'info'); + +echo Leaf\Flash::display(); // message 1 +echo Leaf\Flash::display('info'); // message 2 ```
-## display +## Remove a flash message -This method is used to get a flash message. As soon as the flash message is retrieved, it is removed from the session which means it won't show on the next load. +The `unset()` method allows you to remove a flash message. Note that flash messages are automatically removed when you display them, so you might never need to use this method.
```php -flash()->set("message 1"); -flash()->set("message 2", "info"); - -echo flash()->display(); // message 1 -echo flash()->display("info"); // message 2 +flash()->unset(); +flash()->unset('info'); // unset a specific flash message ```
```php -Leaf\Flash::set("message 1"); -Leaf\Flash::set("message 2", "info"); - -echo Leaf\Flash::display(); // message 1 -echo Leaf\Flash::display("info"); // message 2 +Leaf\Flash::unset(); +Leaf\Flash::unset('info'); // unset a specific flash message ```
-## save +## Permanent flash messages -Flash also allows you to `save` a message in session. This message will stay in session till it is manually removed. Note that unlike regular flashes, there can be only one saved flash message. +Flash also allows you to create a message that stays in session till it is manually removed. You can add permanently stored flash data using the `save()` method. Note that unlike regular flashes, there can be only one saved flash message.
```php -flash()->save("This is my message"); +flash()->save('This is my message'); ```
```php -Leaf\Flash::save("This is my message"); +Leaf\Flash::save('This is my message'); ```
-## clearSaved +## Removing saved flash messages -This is `unset` for saved messages. +You can use the `clearSaved()` method to remove saved flash messages.
@@ -199,9 +191,9 @@ Leaf\Flash::clearSaved();
-## displaySaved +## Displaying saved flash messages -This is `display` for saved messages. +You can use the `displaySaved()` method to display saved flash messages.
diff --git a/src/modules/session/index.md b/src/modules/session/index.md index e516c33c..3261bbde 100755 --- a/src/modules/session/index.md +++ b/src/modules/session/index.md @@ -1,7 +1,13 @@ # Leaf Session -Leaf offers simple session management to help you quickly build your apps and APIs. You can quickly install leaf session with composer or leaf cli. +Given that HTTP-driven applications lack statefulness, sessions offer a means of retaining user-related data throughout multiple requests. Usually, this user information is stored in some sort of persistent storage so it can be accessed on subsequent requests. + +Although using sessions in PHP is fairly straightforward, it can be a bit cumbersome at times. Leaf session aims to make working with sessions in PHP much easier, more enjoyable, and more testable. For that reason, Leaf provides the session module to help you manage sessions in your Leaf apps. *Leaf session is 100% compatible with native PHP sessions.* + +## Installation + +You can install leaf session with the Leaf CLI tool: ```bash leaf install session @@ -13,489 +19,552 @@ or with composer: composer require leafs/session ``` -## Using Session +## Functional Mode -
+When using Leaf session in a Leaf 3 app, you can use the functional mode. This allows you to use the session module without having to initialize it. This gives you access to the `session()` and [`flash()`](/modules/session/flash#functional-mode) helper functions. -### Functional mode - +## Starting a new session -Leaf session also hooks into leaf 3's functional mode. If you are using leaf 3, then this is the fastest way to use the session class. +Leaf's session module smartly handles session initialization. It checks if a session has already been started and starts a new one if it hasn't. This means you don't have to worry about starting a session before using it. Note that Leaf will not start a session until you actually use it. This is to prevent unnecessary session initialization. -#### session +You also don't have to worry about messing up your sessions since Leaf session is 100% compatible with native PHP sessions. -`session` is a global method that can be used to create a session or return the session object. +## Retrieving session data -```php -session()->set("name", "Michael"); -``` +Leaf session provides 3 ways to retrieve session data: -With the above example, no session already exists, so leaf session will create a new one and set the name variable. +- The `get()` method +- The `retrieve()` method +- The `body()` method -You can call any session method on the `session` function: +### The `get()` method -```php -session()->destroy(); -``` +`get()` is a simple method that returns a session value. It takes in 3 parameters: -#### flash +- The name of the value to return. It works just like how `$_SESSION['key']` does. +- The default value to use if it doesn't exist. +- A boolean value indicating whether to sanitize the value or not. It has a default value of true. -This is a simple class for getting and setting flash data or returning the leaf flash object. +
```php -# return leaf session flash object -flash()->set("This is a message"); +$session = new Leaf\Http\Session; + +... + +$item = $session->get('item'); +$item = $session->get('item', 'default value'); +$item = $session->get('item', 'default value', false); ```
-
+
-### Session Class +```php +$item = session()->get('item'); +$item = session()->get('item', 'default value'); +$item = session()->get('item', 'default value', false); +``` -You can quickly get started with Leaf session by using the `Leaf\Http\Session` class. +
-```php +You can also return many fields at once from the session by passing an array of keys: -require __DIR__ . "/vendor/autoload.php"; +
-$app = new Leaf\App; +```php{5} $session = new Leaf\Http\Session; -$app->get("/text", function () use($session) { - $session->set("name", "Michael Darko"); -}); -``` +... -
+$user = $session->get(['username', 'email']); -
+... -## Starting a new session +echo $user['username']; +``` -A new session is started or an old one continued when you instanciate the `Leaf\Http\Session`. +
+
-```php -// new session not started -$session = new Leaf\Http\Session(false); +```php{1} +$user = session()->get(['username', 'email']); -// new session/continue session -$session = new Leaf\Http\Session; +... -// new session/continue session -$session = new Leaf\Http\Session(true); +echo $user['username']; ``` -Since we want to avoid sessions conflicting, Leaf allows you to choose whether you want to start a new session on init. This also allows smooth integration with native PHP sessions, so you can always switch to Leaf sessions when you're ready. +
-Also, since leaf session is 100% compatible with native PHP sessions, you can use the `session_start` method if you need to. +### The `retrieve()` method -When using leaf sessions staticly, there's no need for the above methods, just go straight for which ever you need to use. +`retrieve()` returns the requested value just like `get()` above **and then immediately removes it from the session**, so it can only be retrieved once. -```php -$sessionBody = Leaf\Http\Session::body(); -``` +It takes in three parameters: -Or +- The name of the value to return. It works just like how `$_SESSION['key']` does. +- The default value to use if it doesn't exist. +- A boolean value indicating whether to sanitize the value or not. It has a default value of true. + +
```php -use Leaf\Http\Session; +$session = new Leaf\Http\Session; + +... -$sessionBody = Session::body(); +$item = $session->retrieve('item'); +$item = $session->retrieve('item', 'default value'); +$item = $session->retrieve('item', 'default value', false); ```
+
-## Leaf Session Methods +```php +$item = session()->retrieve('item'); +$item = session()->retrieve('item', 'default value'); +$item = session()->retrieve('item', 'default value', false); +``` -From this point on you'll be able to use everything Leaf Sessions have to offer. Let's look at the session methods. +
-### set +### The `body()` method -set simply sets new native session variables for your app. +This method returns the {key => value} pairs of all the session data including any CSRF data as an associative array.
```php -$session->set("username", $username); +$session = new Leaf\Http\Session; + +... + +$body = $session->body(); ```
```php -session()->set("username", $username); +$body = session()->body(); ```
-- Setting multiple values +## Check if a session value exists -`set` can take in an array if you wish to set multiple values or just want to use one. +You can check if a session value exists with the `has()` method. It takes in the name of the value to check for and returns a boolean value.
```php -$session->set([ - "username" => $username, - "mobile_number" => $mobile_number -]); +$session = new Leaf\Http\Session; + +... + +if ($session->has('item')) { + // do something +} ```
```php -session()->set([ - "username" => $username, - "mobile_number" => $mobile_number -]); +if (session()->has('item')) { + // do something +} ```
-### get - -get is a simple method that returns a session value. It takes in one parameter: the name of the param passed into the app through the session It works just like how `$_SESSION['key']` does. +By default, `has()` will return `true` **ONLY if the value exists and is NOT empty**. You can change this behaviour by passing in `false` as the second parameter. This boolean value indicates whether to check if the value is empty or not. It has a default value of true.
```php -$item = $session->get('item'); +$session = new Leaf\Http\Session; + +... + +if ($session->has('item', false)) { + // do something +} ```
```php -$item = session()->get('item'); +if (session()->has('item', false)) { + // do something +} ```
-- Multiple Get +## Setting session data + +The session module provides a simple way to set session data using the `set()` method. It takes in two parameters: -You can also return many fields at once from the session: +- The name of the value to set. +- The value to set.
```php -$user = $session->get(["username", "email"]); +$session = new Leaf\Http\Session; + +... + +$session->set('item', 'value'); ```
```php -$user = session()->get(["username", "email"]); +session()->set('item', 'value'); ```
-- Security Fixes - -`set` has also received a bunch of security fixes which prevent maliscious scripts from being passed into your application. You can choose to turn this feature off, maybe for html values: +You can also set multiple values at once by passing in an array:
```php -// turn off sanitize -$html = $session->get("blog", false); +$session = new Leaf\Http\Session; + +... + +$session->set([ + 'item1' => 'value1', + 'item2' => 'value2' +]); ```
```php -// turn off sanitize -$html = session()->get("blog", false); +session()->set([ + 'item1' => 'value1', + 'item2' => 'value2' +]); ```
-### retrieve - -`retrieve` returns the requested value and removes it from the session, just like calling `get` first and then `unset` for the same key. +## Removing session data -It takes in two parameters: - -- the name of the param you want to get It works just like how `$_SESSION['key']` does -- The default value to use if it doesn't exist. +Leaf provides a simple `unset()` method to remove session data. It takes in the name of the value to remove.
```php -$username = $session->retrieve("username"); +$session = new Leaf\Http\Session; + +... + +// remove single item +$session->unset('email'); + +// remove multiple items +$session->unset(['name', 'email']); ```
```php -$username = session()->retrieve("username"); +// remove single item +session()->unset('email'); + +// remove multiple items +session()->unset(['name', 'email']); ```
-### body +## Working with Arrays -This method returns the {key => value} pairs of all the session data including any CSRF data as an associative array. +Leaf session allows you to neatly handle working with arrays in session. You can set, retrieve and validate session values from arrays by using the dot notation:
```php -$body = $session->body(); +$session = new Leaf\Http\Session; + +... + +// $user = ['username' => 'leaf', 'email' => 'leaf@example']; + +$username = $session->get('user.username'); +$email = $session->get('user.email'); ```
```php -$body = session()->body(); +// $user = ['username' => 'leaf', 'email' => 'leaf@example']; + +$username = session()->get('user.username'); +$email = session()->get('user.email'); ```
-### unset +This works for `retrieve()`, `has()`, `set()` and `unset()` as well. -`unset` simply deletes a session variable. You can also delete multiple values at once. +**has:**
```php -// single value -$session->unset('email'); +$session = new Leaf\Http\Session; -// multiple values -$session->unset(['name', 'email']); +... + +if ($session->has('user.username')) { + // do something +} + +// allow empty values +if ($session->has('user.username', false)) { + // do something +} ```
```php -// single value -session()->unset('email'); +if (session()->has('user.username')) { + // do something +} -// multiple values -session()->unset(['name', 'email']); +// allow empty values +if (session()->has('user.username', false)) { + // do something +} ```
-### reset - -`reset` simply re-initialises a session. +**Set:**
```php -$app->post('/session/reset', function () use($session) { - $session->reset(); -}); +$session = new Leaf\Http\Session; + +... + +$session->set('user.username', 'leaf'); ```
```php -app()->post('/session/reset', function () { - session()->reset(); -}); +session()->set('user.username', 'leaf'); ```
-### id - -`id` sets and/or returns the current session id. It takes in an **optional** parameter: the ID to overwrite the session id. +**Unset:**
```php -$id = $session->id(); +$session = new Leaf\Http\Session; + +... + +$session->unset('user.username'); ```
```php -$id = session()->id(); +session()->unset('user.username'); ```
-So if the session id is not set, this will generate and return a new session id. However, if the session id is already set, it will just return it. +## Session flash -You can also set your own session id with this syntax below. It will be returned as well, so you can keep it in a variable. +Leaf session also provides built-in support for flash messages. Flash messages are temporary messages that are displayed to the user after an action has been performed. They are usually used to display success or error messages to the user.
```php -$id = $session->id("new session id"); +$session = new Leaf\Http\Session; + +$session->flash("my flash message"); + +echo $session->flash(); // my flash message ```
```php -$id = session()->id("new session id"); +session()->flash("my flash message"); + +echo session()->flash(); // my flash message ```
-### regenerate +For more advanced uses of flash messages, you can check out the [Flash Session docs](/modules/session/flash). + +## Session Internals + +Leaf session provides a few methods to help you manage sessions. These methods are: -regenerate simply generates a new session id. It takes in a boolean parameter which indicates whether to delete all session data or not(has a default of false) +### reset() + +You can use the `reset()` method to re-initialize a session.
```php -$session->regenerate(); -$session->regenerate(false); -$session->regenerate(true); // will clear all session data +$app->post('/session/reset', function () use($session) { + $session->reset(); +}); ```
```php -session()->regenerate(); -session()->regenerate(false); -session()->regenerate(true); // will clear all session data +app()->post('/session/reset', function () { + session()->reset(); +}); ```
-### destroy +### id() -You can end a session with `destroy`. +`id()` sets and/or returns the current session id. It takes in an **optional** parameter: the ID to overwrite the session id.
```php -$session->destroy(); +$id = $session->id(); ```
```php -session()->destroy(); +$id = session()->id(); ```
-### encode +If the session id is not set, this will generate and return a new session id. However, if the session id is already set, it will just return it. -This feature allows you to encode the current session data as a string. +You can also set your own session id with this syntax below. It will be returned as well, so you can keep it in a variable.
```php -$sessionString = $session->encode(); +$id = $session->id("new session id"); ```
```php -$sessionString = session()->encode(); +$id = session()->id("new session id"); ```
-### decode +### regenerate() -You can also decode a serialized session using the `decode` method. It takes in the string to decode and returns true on success, false on failure. +This method generates a new session id. It takes in a boolean parameter which indicates whether to delete all session data or not (has a default of false)
```php -$success = $session->decode($sessionString); +$session->regenerate(); +$session->regenerate(false); +$session->regenerate(true); // will clear all session data ```
```php -$success = session()->decode($sessionString); +session()->regenerate(); +session()->regenerate(false); +session()->regenerate(true); // will clear all session data ```
-## Session flash +### destroy() -Leaf now provides extensive support for flash messages utilizing `Leaf\Flash`. This functionality is now available on the session method in the form of `flash`. You can set and get flash messages using this method. +You can end a session with `destroy`.
```php -$session = new Leaf\Http\Session; - -$session->flash("my flash message"); - -echo $session->flash(); // my flash message +$session->destroy(); ```
```php -session()->flash("my flash message"); - -echo session()->flash(); // my flash message +session()->destroy(); ```
-For more advanced uses of flash messages, you can check out the [Flash Session](/modules/session/flash) documentation. +### encode() -## Error Handling - -If any of the above methods fail an operation, `false` is returned and an error is left in the `Leaf\Http\Session` local state. This error or errors can be returned by calling the `errors` method. +This feature allows you to encode the current session data as a string.
```php -$user = $session->get("user"); - -if (!$user) $response->exit($session->errors()); +$sessionString = $session->encode(); ```
```php -$user = session()->get("user"); - -if (!$user) { - response()->exit(session()->errors()); -} +$sessionString = session()->encode(); ```
-As you can see, you'd manually need to throw errors, this gives you more flexibility in web apps, so instead of throwing session errors, you might do something like this: +### decode() + +You can also decode a serialized session using the `decode()` method. It takes in the string to decode and returns true on success, false on failure.
```php -errors() as $error => $value) { - echo "{$value}"; -} +$success = $session->decode($sessionString); ```
```php -errors() as $error => $value) { - echo "{$value}"; -} +$success = session()->decode($sessionString); ```
From af97e7a4cec0d9bc73cdfa78bad331abb55ffcd2 Mon Sep 17 00:00:00 2001 From: mychidarko Date: Sun, 9 Jul 2023 19:20:59 +0000 Subject: [PATCH 4/4] feat: update session docs --- src/modules/session/flash.md | 2 +- src/modules/session/index.md | 79 ++++++++++++++++++++++++++++++++++++ 2 files changed, 80 insertions(+), 1 deletion(-) diff --git a/src/modules/session/flash.md b/src/modules/session/flash.md index 7030baab..a66d9400 100755 --- a/src/modules/session/flash.md +++ b/src/modules/session/flash.md @@ -13,7 +13,7 @@ Using the `config()` method, you can change where Leaf stores flash messages in - key: The key to save flash array in session. Default: `leaf.flash`, - default: The key for default flash messages. Default: `message`, -- saved: The key for saved flash messages. Default: `leaf.flash.saved`, +- saved: The key for saved flash messages. Default: `leaf.flashSaved`,
diff --git a/src/modules/session/index.md b/src/modules/session/index.md index 3261bbde..75dd7009 100755 --- a/src/modules/session/index.md +++ b/src/modules/session/index.md @@ -29,6 +29,29 @@ Leaf's session module smartly handles session initialization. It checks if a ses You also don't have to worry about messing up your sessions since Leaf session is 100% compatible with native PHP sessions. +### Manually starting a session + +If you want to manually start a session, you can use the `start()` method. + +
+ +```php +$session = new Leaf\Http\Session; + +... + +$session->start(); +``` + +
+
+ +```php +session()->start(); +``` + +
+ ## Retrieving session data Leaf session provides 3 ways to retrieve session data: @@ -289,6 +312,62 @@ session()->unset(['name', 'email']);
+We also added the `delete()` method as an alias for `unset()`. They both do the same thing. + +
+ +```php +$session = new Leaf\Http\Session; + +... + +// remove single item +$session->delete('email'); + +// remove multiple items +$session->delete(['name', 'email']); +``` + +
+
+ +```php +// remove single item +session()->delete('email'); + +// remove multiple items +session()->delete(['name', 'email']); +``` + +
+ +## Wiping session data + +Leaf Session allows you to wipe all session data with the `clear()` method. This method completely deletes all session information, but does not destroy the session itself. + +
+ +```php +$session = new Leaf\Http\Session; + +... + +$session->clear(); + +echo json_encode($_SESSION); // {} +``` + +
+
+ +```php +session()->clear(); + +echo json_encode($_SESSION); // {} +``` + +
+ ## Working with Arrays Leaf session allows you to neatly handle working with arrays in session. You can set, retrieve and validate session values from arrays by using the dot notation: