PHP code example of bear / resource

1. Go to this page and download the library: Download bear/resource library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

bear / resource example snippets



namespace MyVendor\Sandbox\Blog;

class Author extends ResourceObject
{
    public $code = 200;

    public $headers = [
        'Content-Type' => 'application/json'
    ];

    public $body = [
        'id' =>1,
        'name' => 'koriym'
    ];

    /**
     * @Link(rel="blog", href="app://self/blog/post?author_id={id}")
     */
    public function onGet(int $id): static
    {
        return $this;
    }

    public function onPost(string $name): static
    {
        $this->code = 201; // created
        // ...
        return $this;
    }

    public function onPut(int $id, string $name): static
    {
        $this->code = 204; // no content
        //...
        return $this;
    }

    public function onDelete($id): static
    {
        $this->code = 204; // no content
        //...
        return $this;
    }
}

use BEAR\Resource\ResourceInterface;

$resource = (new Injector(new ResourceModule('FakeVendor/Sandbox')))->getInstance(ResourceInterface::class);

$user = $resource->get('app://self/user', ['id' => 1]);

var_dump($user->body);

Array
(
 [name] => Athos
 [age] => 15
 [blog_id] => 0
)

$user = $resource
  ->get
  ->uri('app://self/user')
  ->withQuery(['id' => 1])
  ->eager
  ->request();

$user = $resource->get->uri('app://self/user')(['id' => 1]);

$user = $resource->uri('app://self/user')(['id' => 1]); // 'get' request method can be omitted

// get `ResourceRequest` objcet 
$user = $resource->get->uri('app://self/user')->withQuery(['id' => 1]);
// assign to the template
echo "User resource body is {$user}"; // same in the template enigne template

// invoke
$user1 = $user(); // $id = 1
$user2 = $user(['id' => 2);

use BEAR\Resource\Annotation\Link;

#[Link(rel: 'blog', href: 'app://self/blog?author_id={id}')]

/**
 * @Link(rel="blog", href="app://self/blog?author_id={id}")
 */

$blog = $resource
    ->get
    ->uri('app://self/user')
    ->withQuery(['id' => 0])
    ->linkSelf('blog')
    ->eager
    ->request();

$user = $resource
    ->get
    ->uri('app://self/user')
    ->withQuery(['id' => 0])
    ->linkNew('blog')
    ->eager
    ->request();

$blog = $user['blog'];

#[Link(rel: 'post-tree', href: 'app://self/post?author_id={id}')]
public function onGet($id = null)

#[Link(crawl='post-tree', rel: 'meta', href: 'app://self/meta?post_id={id}')]
#[Link(crawl='post-tree', rel: 'tag', href: 'app://self/tag?post_id={id}')]
public function onGet($author_id)
{

#[Link(crawl='post-tree', rel: 'tag_name', href: 'app://self/tag/name?tag_id={tag_id}')]
public function onGet($post_id)

$graph = $resource
  ->get
  ->uri('app://self/marshal/author')
  ->linkCrawl('post-tree')
  ->eager
  ->request();

/**
 * @Link(rel="payment", href="app://self/payment{?order_id, credit_card_number, expires, name, amount}", method="put")
 */
public function onPost($drink)

    $order = $resource
        ->post
        ->uri('app://self/order')
        ->withQuery(['drink' => 'latte'])
        ->eager
        ->request();

    $payment = [
        'credit_card_number' => '123456789',
        'expires' => '07/07',
        'name' => 'Koriym',
        'amount' => '4.00'
    ];

    // Now use a hyperlink to pay
    $response = $resource->href('payment', $payment);

    echo $response->code; // 201
?start_inline
use Ray\WebContextParam\Annotation\QueryParam;

class News extends ResourceObject
{
    public function foo(#[QueryParam] string $id) : ResourceObject
    {
      // $id = $_GET['id'];
?start_inline
use Ray\WebContextParam\Annotation\CookieParam;

class News extends ResourceObject
{
    #[CookieParam(key: 'id'] 
    public function foo(string $tokenId) : ResourceObject
    {
      // $tokenId = $_COOKIE['id'];


use Ray\WebContextParam\Annotation\QueryParam;
use Ray\WebContextParam\Annotation\CookieParam;
use Ray\WebContextParam\Annotation\EnvParam;
use Ray\WebContextParam\Annotation\FormParam;
use Ray\WebContextParam\Annotation\ServerParam;

class News extends ResourceObject
{
    public function onGet(
        #[QueryParam('use_id')] string $userId,        // $_GET['use_id'];
        #[CookieParam('id')] string $tokenId,          // $_COOKIE['id'] or "0000" when unset;
        #[EnvParam('app_mode')] string $app_mode,      // $_ENV['app_mode'];
        #[FormParam('token')] string $token,           // $_POST['token'];
        #[ServerParam('SERVER_NAME') #server           // $_SERVER['SERVER_NAME'];
    ) : ResourceObject {
?start_inline
use BEAR\Resource\Annotation\ResourceParam;

class News extends ResourceObject
{
    /**
     * @ResourceParam(param=“name”, uri="app://self//login#nickname")
     */
    public function onGet(string $name) : ResourceObject
    {

$modules = [new ResourceModule('MyVendor\Sandbox'), new JsonModule]:
$resource = Injector::create(modules)
  ->getInstance('BEAR\Resource\ResourceInterface');

echo $user;

// {
//     "name": "Aramis",
//     "age": 16,
//     "blog_id": 1
// }


echo $user['name'];

// Aramis

echo $user->onGet(2);

// {
//     "name": "Yumi",
//     "age": 15,
//     "blog_id": 2
// }

$user = $resource
  ->get
  ->uri('app://self/user')
  ->withQuery(['id' => 1])
  ->request();

$smarty->assign('user', $user);

class News extends ResourceObject
{
    #[Embed(rel: 'weather', src: 'app://self/weather/today')]
    public function onGet(): static
    {
        $this->body = [
            'headline' => "...",
            'sports'] = "..."
        ];
        
        return $this;
    }
}

    // create resource client with HalModule
    $resource = (new Injector(new HalModule(new ResourceModule('FakeVendor\Sandbox'))))->getInstance(ResourceInterface::class);
    // request
    $news = $resource
        ->get
        ->uri('app://self/news')
        ->withQuery(['date' => 'today'])
        ->request();
    // output
    echo $news . PHP_EOL;

$userView = (string) $resource->get('app://self/user?id=1');
echo $userView; // get JSON

class User extends ResourceObject
{
    public function __construct()
    {
        $this->setRenderer(new class implements RenderInterface{
            public function render(ResourceObject $ro)
            {
                $ro->headers['content-type'] = 'application/json';
                $ro->view = json_encode($ro->body);

                return $ro->view;
            }
        });
    }
}

$user = $resource->get('app://self/user?id=1');
$user->transfer(new class implements TransferInterface {
	public function __invoke(ResourceObject $ro, array $server)
	{
	    foreach ($ro->headers as $label => $value) {
	        header("{$label}: {$value}", false);
	    }
	    http_response_code($ro->code);
	    echo $ro->view;
	}
);


use BEAR\Resource\ResourceInterface;

// save
$resource = (new Injector(new ResourceModule('FakeVendor/Sandbox')))->getInstance(ResourceInterface::class);
$cachedResource = serialize($resource);

// load
$resource = unserialize($cachedResource);
$news = $resource->get('app://self/news');

var_export($graph->body);

array (
    0 =>
    array (
        'name' => 'Athos',
        'post' =>
        array (
            0 =>
            array (
                'author_id' => '1',
                'body' => 'Anna post #1',
                'meta' =>
                array (
                    0 =>
                    array (
                        'data' => 'meta 1',
                    ),
                ),
                'tag' =>
                array (
                    0 =>
                    array (
                        'tag_name' =>
                        array (
                            0 =>
                            array (
                                'name' => 'zim',
                            ),
                        ),
                    ),
 ...

composer create-project bear/resource BEAR.Resource
cd BEAR.Resource
./vendor/bin/phpunit
php demo/run.php