Skip to content

V6 #12

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open

V6 #12

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 5 additions & 10 deletions the-basics/collections.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ description: >-
You can create a collection in a couple of ways:

```php
use Tightenco\Collect\Support\Collection;
use Illuminate\Support\Collection;

$data = new Collection(['Jayne', 'Milo']);

Expand All @@ -35,19 +35,14 @@ $data = collect(['Jayne', 'Milo']);
$firstName = $data->first();
```

The collection class that Lumberjack uses comes from Laravel, [via a split package by Tighten Co.](https://github.com/tightenco/collect)

For a list of the available methods, please refer to their documentation: [https://laravel.com/docs/5.8/collections\#available-methods](https://laravel.com/docs/5.8/collections#available-methods)
For a list of the available methods, please refer to their documentation: [https://laravel.com/docs/9.x/collections#available-methods](https://laravel.com/docs/9.x/collections#available-methods)

{% hint style="info" %}
Note: Laravel's collections may change over time as the add/remove features etc. Make sure you are always referring to the correct version of their documentation.

Lumberjack will use the latest collections version for Laravel `v5.x` _\(with the minimum version being `v5.6`\)_
Note: Laravel's collections may change over time as they add/remove features etc. Make sure you are always referring to the correct version of their documentation.
{% endhint %}

### Extending collections

Similar to post types and the query builder, you can add your own methods to the collection class using macros. For more information about this, please refer to Laravel's documentation:

[https://laravel.com/docs/5.8/collections\#extending-collections](https://laravel.com/docs/5.8/collections#extending-collections)
Similar to post types and the query builder, you can add your own methods to the collection class using macros. For more information about this, please refer to Laravel's documentation:

[https://laravel.com/docs/9.x/collections#extending-collections](https://laravel.com/docs/9.x/collections#extending-collections)
11 changes: 7 additions & 4 deletions the-basics/http-responses.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,13 @@ return new TimberResponse('home.twig', $context);

When passing context data to TimberResponse, any objects that implement the `Rareloop\Lumberjack\Contracts\Arrayable` contract will automatically be flattened to a standard PHP array. This means that it is safe to use objects such as `Collection` and `ViewModel` in your data without it causing issues with Twig.

{% page-ref page="view-models.md" %}
{% content-ref url="view-models.md" %}
[view-models.md](view-models.md)
{% endcontent-ref %}

{% page-ref page="collections.md" %}
{% content-ref url="collections.md" %}
[collections.md](collections.md)
{% endcontent-ref %}

### Redirect Response

Expand All @@ -57,7 +61,7 @@ return new RedirectResponse('/another/page');
If you want to redirect to a URL and also flash some data to the session, you can use the `with()` method.

```php
return new RedirectResponse('/another/page')
return (new RedirectResponse('/another/page'))
->with('error', 'Something went wrong');
```

Expand Down Expand Up @@ -141,4 +145,3 @@ class TestException extends \Exception implements Responsable
}
}
```

58 changes: 53 additions & 5 deletions the-basics/middleware.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,15 +121,15 @@ To register an alias you can use the `MiddlewareAliases` facade. It is recommend

There are 3 ways to define your middleware alias:

* A closure factory _\(recommended - always creates a new instance when used\)_
* A class name _\(always resolves a new instance from the Container when used\)_
* A previously instantiated object _\(you don't get the benefits of lazy loading\)_
* A closure factory _(recommended - always creates a new instance when used)_
* A class name _(always resolves a new instance from the Container when used)_
* A previously instantiated object _(you don't get the benefits of lazy loading)_

{% hint style="info" %}
_See "_[_Setting entries in the container_](https://app.gitbook.com/@rareloop/s/lumberjack/~/edit/drafts/-Lk9PktE5_xnzl2Zs2j1/container/using-the-container#setting-entries-in-the-container)_" for more information about the differences between these. While only the class name uses the container, principally they behave in the same way with regards to lazy-loading and object instantiation_.
_See "_[_Setting entries in the container_](https://app.gitbook.com/@rareloop/s/lumberjack/\~/edit/drafts/-Lk9PktE5\_xnzl2Zs2j1/container/using-the-container#setting-entries-in-the-container)_" for more information about the differences between these. While only the class name uses the container, principally they behave in the same way with regards to lazy-loading and object instantiation_.
{% endhint %}

#### Using a closure factory \(recommended\)
#### Using a closure factory (recommended)

It is recommended that the alias is registered using a closure that acts as a factory, like so:

Expand Down Expand Up @@ -209,3 +209,51 @@ Router::get(

In this example, `$key` will have the value `X-Key` and `$value` will have the value of `HeaderValue`.

## Creating custom Middleware

While you can use any PSR 15/7 Middleware, sometimes you need to write your own. In this example, we will create custom middleware that adds the response header `X-Foo`.\
\
First, create the class in `app/Http/Middleware/ExampleMiddleware.php` (create the folder if it doesn't exist) with the following content:

```php
<?php

namespace App\Http\Middleware;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

class ExampleMiddleware implements MiddlewareInterface
{
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$response = $handler->handle($request);

return $response;
}
}
```

In our example, we want to modify the **response**. Below we add the `X-Foo` header to the response:

```php
return $response->withHeader('X-Foo', 'Bar');
```

If you need to modify the request before it gets passed to your application, you can do so before `$handler->handle($request)` gets called:

```php
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
// Chance to modify the request here before passing it into your application

// Pass the request on (to the next middleware or your application)
$response = $handler->handle($request);

// Chance to modify the response here before sending it back

return $response;
}
```
21 changes: 10 additions & 11 deletions the-basics/view-models.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# View Models

View Models are useful for preparing data for your Twig views. It’s common \(and typically desirable\) for the shape of the data needed by your views to be different from how it is stored in the database or Post objects. How this data is transformed can be encapsulated in a View Model, cutting down repetitive code you have in your Controllers.
View Models are useful for preparing data for your Twig views. It’s common (and typically desirable) for the shape of the data needed by your views to be different from how it is stored in the database or Post objects. How this data is transformed can be encapsulated in a View Model, cutting down repetitive code you have in your Controllers.

## Example Controller

Expand Down Expand Up @@ -62,7 +62,7 @@ class MediaCardViewModel extends ViewModel
}
```

Now lets pass in the post object into the view model and keep a \(protected\) reference to it.
Now lets pass in the post object into the view model and keep a (protected) reference to it.

```php
<?php
Expand All @@ -85,7 +85,7 @@ class MediaCardViewModel extends ViewModel

View models are automatically converted to arrays when passed into a `twig` template. **Public methods are used as keys in this array, and the method is executed to get the value.**

Below we have added 3 public methods \(`title`, `description` and `published`\). These are the keys that our view needs.
Below we have added 3 public methods (`title`, `description` and `published`). These are the keys that our view needs.

```php
<?php
Expand Down Expand Up @@ -148,7 +148,7 @@ class SingleController
}
```

The above will ensure the `$context` looks like the following when the view model has been converted to an array \(without having to have prepared the `card` structure in the Controller\):
The above will ensure the `$context` looks like the following when the view model has been converted to an array (without having to have prepared the `card` structure in the Controller):

```php
$context = [
Expand All @@ -163,7 +163,7 @@ $context = [
```

{% hint style="info" %}
Remember: All view models \(and collections\) in the context are automatically flattened to arrays before being passed to `twig` views.
Remember: All view models (and collections) in the context are automatically flattened to arrays before being passed to `twig` views.
{% endhint %}

### Manually converting view models to arrays
Expand Down Expand Up @@ -206,7 +206,7 @@ namespace App\ViewModels;
use Rareloop\Lumberjack\Post;
use Rareloop\Lumberjack\ViewModel;
use App\ViewModels\MediaCardViewModel;
use Tightenco\Collect\Support\Collection;
use Illuminate\Support\Collection;

class MediaCardsViewModel extends ViewModel
{
Expand Down Expand Up @@ -307,7 +307,7 @@ class SingleController
}
```

**In order to keep your view models generic, and your controllers light \(and DRY\) you can create something called a "named constructor" on your view model.**
**In order to keep your view models generic, and your controllers light (and DRY) you can create something called a "named constructor" on your view model.**

This is simply a `static` method on your view model that constructs the view model _for a specific use case_.

Expand Down Expand Up @@ -382,8 +382,8 @@ class SingleController
```

{% hint style="info" %}
You can have multiple named constructors on a view model to construct it with different data. For example you could have a `PostTeasersViewModel` which transforms a collection of posts ready for a list view.
You can have multiple named constructors on a view model to construct it with different data. For example you could have a `PostTeasersViewModel` which transforms a collection of posts ready for a list view.

And you could have the following named constructor:

* `latestPosts($limit = 3)`- which knows how to get the latest _n_ posts.
Expand All @@ -392,9 +392,8 @@ And you could have the following named constructor:

## Using Hatchet

If you are using [hatchet](https://github.com/Rareloop/hatchet) \(Lumberjack's CLI\), you can easily create view models with the following command:
If you are using [hatchet](https://github.com/Rareloop/hatchet) (Lumberjack's CLI), you can easily create view models with the following command:

```bash
php hatchet make:viewmodel TestimonialViewModel
```

39 changes: 37 additions & 2 deletions the-basics/wordpress-controllers.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

## Introduction

In the files \(i.e. controllers\) that WordPress uses when it matches a route \(e.g. `page.php`, `single.php`\), you can now use a class rather than writing procedural code.
In the files (i.e. controllers) that WordPress uses when it matches a route (e.g. `page.php`, `single.php`), you can now use a class rather than writing procedural code.

```php
// page-home.php
Expand Down Expand Up @@ -33,7 +33,7 @@ class PageHomeController
**The name of the controller is important:**

* It should be under the namespace `App`.
* The class name must be an UpperCamelCase version of the filename with the word `Controller` on the end \(without spaces, dashes and underscores\). If the controller name is not correctly Lumberjack will not throw any errors - instead you will just get a blank page.
* The class name must be an UpperCamelCase version of the filename with the word `Controller` on the end (without spaces, dashes and underscores). If the controller name is not correctly Lumberjack will not throw any errors - instead you will just get a blank page.

The `handle` method will automatically be called on your controller.

Expand Down Expand Up @@ -63,3 +63,38 @@ In WordPress, you have a `404.php` file. `PHP` Classes cannot start with a numbe

Instead Lumberjack will look for a controller called `Error404Controller`

## Password protected pages

{% hint style="info" %}
Since: v6.1.0
{% endhint %}

WordPress supports password protection for pages across your site. This is also [supported by Timber](https://timber.github.io/docs/v1/guides/wp-integration/#password-protected-posts) but requires you to implement it in each of your site's templates to take effect universally.

To make this simpler to implement, Lumberjack adds a middleware to handle this across all page templates. When a request is made for a page that requires a password it will intercept the call and attempt to render the `single-password.twig` file instead.

It is recommended that you implement the Twig file in line with what Timber suggests:

```twig
{% raw %}
{% extends "base.twig" %}

{% block content %}
{{ function('get_the_password_form') }}
{% endblock %}
{% endraw %}
```

{% hint style="info" %}
**Note:** If a `single-password.twig` file is **not found,** the middleware will fall back gracefully to the default behaviour, which is to **ignore the password functionality and render the page as normal**.
{% endhint %}

### Changing the Twig file used for password protected pages

If you would like to change the name of the Twig file that is used for password protection you can do so using the `lumberjack/password_protect_template` filter:

```php
add_filter('lumberjack/password_protect_template', function() {
return 'my-password-template.twig';
});
```
Loading