Skip to content
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

Share links to your custom controllers #1037

Open
clysss opened this issue Jun 19, 2024 · 4 comments
Open

Share links to your custom controllers #1037

clysss opened this issue Jun 19, 2024 · 4 comments
Assignees

Comments

@clysss
Copy link
Contributor

clysss commented Jun 19, 2024

hello @mevdschee
I discovered 3 hours ago this repo and it's already close to be in prod ! spend days to try to do the same with adminjs
php-crud-api is a key changer ! never seen such a so effective server tool !

a suggestion : with 3k stars, sure that lot of people is using this, and lot of them have construct custom controllers. Could this thread (or wiki or something else) could help to list them ?
For example, I'm eventualy looking for ctrl to upload/download local files
Thx

@mevdschee mevdschee self-assigned this Jun 19, 2024
@mevdschee
Copy link
Owner

mevdschee commented Jun 19, 2024

never seen such a so effective server tool !

Thank you for your kind words.

Could this thread (or wiki or something else) could help to list them ?

Yes, please share! I'm happy to list them.

For example, I'm eventualy looking for ctrl to upload/download local files

Did you consider storing blob or longblob fields?

@clysss
Copy link
Contributor Author

clysss commented Jun 22, 2024

I'll probably do a better job lately... but for those who are beginning to use php-crud-api as an advanced API to DB, perhaps this code will give them some ideas..

I've here 2 tables,
users (id, password,...
items (id, ...

api.php :

<?php

namespace Tqdev\PhpCrudApi;

use Tqdev\PhpCrudApi\Api;
use Tqdev\PhpCrudApi\Config\Config;
use Tqdev\PhpCrudApi\RequestFactory;
use Tqdev\PhpCrudApi\ResponseUtils;

require 'api.include.php';
include 'MyController.php';
$config = new Config([
     'driver' => 'pgsql',
     'address' => 'xxx,
     'port' => 'xxx',
     'username' => 'xxx',
     'password' => 'xxx',
     'database' => 'xxx',
     'debug' => true,
    'dbAuth.usersTable' => 'users',
    'dbAuth.usernameColumn'=> 'name',
    'dbAuth.passwordColumn' => 'password',
    'dbAuth.returnedColumns' => 'id', 
    'middlewares'=>'dbAuth, authorization',
    'authorization.pathHandler' => function ($path) {
       //default routes : /me /register /login /password /logout /records /status(/ping)
       return !in_array($path,array('register','password','records','xxxstatus'));
    },
]);
$request = RequestFactory::fromGlobals();
$api = new Api($config);
$response = $api->handle($request);
ResponseUtils::output($response);

MyConstroller.php

<?php
// MyController.php

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Tqdev\PhpCrudApi\Cache\Cache;
use Tqdev\PhpCrudApi\Column\ReflectionService;
use Tqdev\PhpCrudApi\Controller\Responder;
use Tqdev\PhpCrudApi\Database\GenericDB;
use Tqdev\PhpCrudApi\Middleware\Router\Router;
use Tqdev\PhpCrudApi\Record\RecordService;

class MyController
{
        const tUsers = "users";
        const tItems = "items";

	private $responder;

	public function __construct(Router $router, Responder $responder, GenericDB $db, ReflectionService $reflection, Cache $cache) 
    {
        $this->router = $router;
        $this->responder = $responder;
        $this->db = $db;
        $this->recordService = new RecordService($db, $reflection);
        //$this->definition = new DefinitionService($db, $reflection);

        $router->register('GET', '/myUser', array($this, 'getMyUser'));
        $router->register('GET', '/item/*/', array($this, 'getItem'));
        $router->register('PUT', '/item/*/', array($this, 'setItem'));
    }

    public function getMyUser(ServerRequestInterface $request): ResponseInterface
    {
       $id=$_SESSION['user']['id'];
       $params = $this->addParams(Tqdev\PhpCrudApi\RequestUtils::getParams($request), 'exclude', 'password');
       $code_record_not_found = Tqdev\PhpCrudApi\Record\ErrorCode::RECORD_NOT_FOUND;
       $resp = $this->recordService->read(self::tUsers, $id, $params);
       if (!$resp) {
            return $this->responder->error($code_record_not_found, $id);
       }
       return $this->responder->success(['results' => $resp]);

       //version with list
       //$filter = "id,eq,{$_SESSION['user']['id']}";
       //$params = $this->addParams(Tqdev\PhpCrudApi\RequestUtils::getParams($request), 'filter', $filter);
       //$resp = $this->recordService->_list(self::tUsers, $params);
       //return $this->responder->success(['results' => $resp]);
    }

    public function getItem(ServerRequestInterface $request): ResponseInterface
    {
       $id = Tqdev\PhpCrudApi\RequestUtils::getPathSegment($request, 2);
       $params = Tqdev\PhpCrudApi\RequestUtils::getParams($request); 
       $code_record_not_found = Tqdev\PhpCrudApi\Record\ErrorCode::RECORD_NOT_FOUND;
       $resp = $this->recordService->read(self::tItems, $id, $params);
       if (!$resp) {
            return $this->responder->error($code_record_not_found, $id);
       }
       return $this->responder->success(['results' => $resp]);
    }

    public function setItem(ServerRequestInterface $request): ResponseInterface
    {
       $id = Tqdev\PhpCrudApi\RequestUtils::getPathSegment($request, 2);
       $params = Tqdev\PhpCrudApi\RequestUtils::getParams($request); 
       $record = $request->getParsedBody();
       return $this->responder->success($this->recordService->update(self::tItems, $id, $record, $params));
    }


    private function addParams(array $pparams, string $kkey, string $vvalue) : array
    {
       if (is_null($pparams[$kkey])) $pparams[$kkey][]=$vvalue; else array_unshift($pparams[$kkey],$vvalue);  //array_push($pparams[$kkey],$vvalue);
       return $pparams;
    }
}			

don't hesite to ask or comment...

@clysss
Copy link
Contributor Author

clysss commented Jun 22, 2024

I add my own comment / question : about json middleware
if I change :
'middlewares'=>'dbAuth, json, authorization',
and try to put JSON during setItem
for example making this call to PUT /item/{ID}
with (body) :
{"col1":"xx","col2": {"xxx":"vv","yyy":"dd"}} ==>> KO :(
(the update crash without message)
but
{"col1":"xx","col2": "{"xxx":"vv","publDatas":"dd"}"} ==>> ok!
[of course, the 2nd option works also without json middleware]
So, why the json middleware is not active ?
is it because of the call to recordService ? should i call other function ? I don't understand really the way the jsonmiddleware work around the recordService...

@mevdschee
Copy link
Owner

(the update crash without message)

please dig deeper, there must be at least a PHP error in the Apache error log.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants