php Slim-Http-Response类(方法)实例源码

下面列出了php Slim-Http-Response 类(方法)源码代码实例,从而了解它的用法。

作者:joppuy    项目:Dullaha   
public function getUserDetails(Request $request, Response $response, $arguments)
 {
     $user = $this->container->user;
     if ($user) {
         return $response->withJson($user, 200, JSON_PRETTY_PRINT);
     }
 }

作者:neilmillar    项目:fxtrade   
public function test(Request $request, Response $response, array $args)
 {
     $uid = $args['uid'];
     $myaccount = R::load('accounts', $uid);
     $accountId = $myaccount->accountid;
     $account = R::findOne('accounts', ' accountid = ?', [$accountId]);
     if (!empty($account)) {
         $apiKey = $account['apikey'];
         $type = $account['servertype'];
         $oandaInfo = new Broker_Oanda($type, $apiKey, $accountId);
     } else {
         $this->flash->addMessage('flash', "Oanda AccountId not found");
         return $response->withRedirect($request->getUri()->getBaseUrl() . $this->router->pathFor('homepage'));
     }
     $side = 'buy';
     $pair = 'EUR_USD';
     $price = '1.1400';
     $expiry = time() + 60;
     $stopLoss = '1.1300';
     $takeProfit = NULL;
     $risk = 1;
     //        $side='buy';
     //        $pair='GBP_CHF';
     //        $price='2.1443';
     //        $expiry = $oandaInfo->getExpiry(time()+60);
     //        $stopLoss='2.1452';
     //        $takeProfit=NULL;
     //        $risk=1;
     //$oandaInfo->placeLimitOrder($side,$pair,$price,$expiry,$stopLoss,$takeProfit,$risk);
     $oandaInfo->processTransactions();
 }

作者:eella    项目:gredu_lab   
public function __invoke(Request $req, Response $res)
 {
     $school = $req->getAttribute('school', false);
     if (!$school) {
         return $res->withStatus(403, 'No school');
     }
     $teacherId = $req->getParam('teacher_id');
     $teacher = $this->staffService->getTeacherById($teacherId);
     if ($teacher['school_id'] !== $school->id) {
         return $res->withStatus(403, 'No school');
     }
     if ($req->isPost()) {
         $inputFilter = $this->inputFilter;
         $result = $inputFilter($req->getParams());
         if (!$result['is_valid']) {
             $res = $res->withStatus(422);
             $res = $res->withJson($result);
             return $res;
         }
         $this->service->saveAnswers($teacherId, $result['values']);
     }
     $data = $this->service->getAnswers($teacherId);
     $res = $res->withJson($data);
     return $res;
 }

作者:ansa    项目:php-componen   
/**
  * Execute the middleware.
  *
  * @param ExtendedRequest $request
  * @param Response        $response
  * @param callable        $next
  *
  * @return Response
  */
 public function __invoke(ExtendedRequest $request, Response $response, callable $next)
 {
     $router = $this->router;
     $route = $request->getCurrentRoute();
     $locales = $this->locale;
     $locale = $locales->getDefault();
     $lang = $route->getArgument($router->getLanguageIdentifier());
     $lang = ltrim($lang, '/');
     $redirect = false;
     if ($lang) {
         try {
             // Find language in list of available locales and set it as active
             $locale = $locales->findByLanguage($lang);
             $locales->setActive($locale);
             if ($router->isOmitDefaultLanguage() && $locale == $locales->getDefault()) {
                 // Trigger redirect to correct path (as language set in path is default lang and we want to omit it)
                 $redirect = true;
             }
         } catch (Exception $e) {
             // Trigger "notFound" as setActive() throws Exception if $locale is not valid / available
             $next = $this->notFoundHandler;
         }
     } elseif (!$router->isOmitDefaultLanguage()) {
         // Trigger redirect to correct path (as language is not set in path but we don't want to omit default lang)
         $redirect = true;
     }
     // Redirect to route with proper language identifier value set (or omitted)
     if ($redirect) {
         $path = $router->pathFor($route->getName(), $route->getArguments(), $request->getParams(), $locale->getLanguage());
         $uri = $request->getUri()->withPath($path);
         return $response->withRedirect($uri);
     }
     return $next($request, $response);
 }

作者:bigpoin    项目:slim-bootstra   
/**
  * This function outputs the given $data as valid HAL+JSON to the client
  * and sets the HTTP Response Code to the given $statusCode.
  *
  * @param array|SlimBootstrap\DataObject $data       The data to output to
  *                                                   the client
  * @param int                            $statusCode The status code to set
  *                                                   in the reponse
  */
 public function write($data, $statusCode = 200)
 {
     $path = $this->_request->getPath();
     $hal = new hal\Hal($path);
     if (true === is_array($data)) {
         $pathData = explode('/', $path);
         unset($pathData[0]);
         $endpointName = end($pathData);
         $endpointUri = '/' . implode('/', $pathData) . '/';
         foreach ($data as $entry) {
             /** @var SlimBootstrap\DataObject $entry */
             $identifiers = $entry->getIdentifiers();
             $resourceName = $endpointUri . implode('/', array_values($identifiers));
             $resource = new hal\Hal($resourceName, $entry->getData() + $entry->getIdentifiers());
             $this->_addAdditionalLinks($resource, $entry->getLinks());
             $hal->addLink($endpointName, $resourceName);
             $hal->addResource($endpointName, $resource);
         }
     } else {
         $hal->setData($data->getData() + $data->getIdentifiers());
         $this->_addAdditionalLinks($hal, $data->getLinks());
     }
     $body = $this->_jsonEncode($hal);
     if (false === $body) {
         $this->_response->setStatus(500);
         $this->_response->setBody("Error encoding requested data.");
         return;
     }
     $this->_headers->set('Content-Type', 'application/hal+json; charset=UTF-8');
     $this->_response->setStatus($statusCode);
     $this->_response->setBody($hal->asJson());
 }

作者:ninjaner    项目:slim-skeleto   
/**
  * Execute the middleware.
  *
  * @param  \Slim\Http\Request  $req
  * @param  \Slim\Http\Response $res
  * @param  callable            $next
  * @return \Slim\Http\Response
  */
 public function __invoke(Request $req, Response $res, callable $next)
 {
     $uri = $req->getUri();
     $path = $this->filterTrailingSlash($uri);
     if ($uri->getPath() !== $path) {
         return $res->withStatus(301)->withHeader('Location', $path)->withBody($req->getBody());
     }
     //        if ($this->filterBaseurl($uri)) {
     //            return $res->withStatus(301)
     //                ->withHeader('Location', (string) $uri)
     //                ->withBody($req->getBody());
     //        }
     $server = $req->getServerParams();
     if (!isset($server['REQUEST_TIME_FLOAT'])) {
         $server['REQUEST_TIME_FLOAT'] = microtime(true);
     }
     $uri = $uri->withPath($path);
     $req = $this->filterRequestMethod($req->withUri($uri));
     $res = $next($req, $res);
     $res = $this->filterPrivateRoutes($uri, $res);
     // Only provide response calculation time in non-production env, tho.
     if ($this->settings['mode'] !== 'production') {
         $time = (microtime(true) - $server['REQUEST_TIME_FLOAT']) * 1000;
         $res = $res->withHeader('X-Response-Time', sprintf('%2.3fms', $time));
     }
     return $res;
 }

作者:GreatOw    项目:OwlPelle   
public function __invoke(Request $request, Response $response, $arguments)
 {
     $response->write('this is just the beginning of my application');
     foreach ($arguments as $argument) {
         $response->write("\n {$argument}");
     }
 }

作者:nui    项目:gi   
public function learningcenterRemove(Request $req, Response $res, $attr = [])
 {
     $container = $this->slim->getContainer();
     $db = $container->medoo;
     $db->delete("learningcenter", ["id" => $attr["id"]]);
     return $res->withHeader("Location", $req->getUri()->getBasePath() . "/learningcenter");
 }

作者:jensseger    项目:lea   
/**
  * {@inheritdoc}
  */
 public function register()
 {
     $this->getContainer()->share('settings', function () {
         return new Collection($this->defaultSettings);
     });
     $this->getContainer()->share('environment', function () {
         return new Environment($_SERVER);
     });
     $this->getContainer()->share('request', function () {
         return Request::createFromEnvironment($this->getContainer()->get('environment'));
     });
     $this->getContainer()->share('response', function () {
         $headers = new Headers(['Content-Type' => 'text/html']);
         $response = new Response(200, $headers);
         return $response->withProtocolVersion($this->getContainer()->get('settings')['httpVersion']);
     });
     $this->getContainer()->share('router', function () {
         return new Router();
     });
     $this->getContainer()->share('foundHandler', function () {
         return new RequestResponse();
     });
     $this->getContainer()->share('errorHandler', function () {
         return new Error($this->getContainer()->get('settings')['displayErrorDetails']);
     });
     $this->getContainer()->share('notFoundHandler', function () {
         return new NotFound();
     });
     $this->getContainer()->share('notAllowedHandler', function () {
         return new NotAllowed();
     });
     $this->getContainer()->share('callableResolver', function () {
         return new CallableResolver($this->getContainer());
     });
 }

作者:eella    项目:gredu_lab   
public function __invoke(Request $req, Response $res, array $args = [])
 {
     $school = $req->getAttribute('school', false);
     if (!$school) {
         return $res->withStatus(403, 'No school');
     }
     $params = $req->getParams();
     $id = $params['id'];
     $params['school_id'] = $school->id;
     if (isset($params['lessons']) && !is_array($params['lessons'])) {
         $params['lessons'] = explode(',', $params['lessons']);
     }
     unset($params['id']);
     try {
         if ($id) {
             $lab = $this->labservice->updateLab($params, $id);
             $res = $res->withStatus(200);
         } else {
             $lab = $this->labservice->createLab($params);
             $res = $res->withStatus(201);
         }
         $res = $res->withJson($lab);
     } catch (Exception $ex) {
         $res = $res->withStatus(500, $ex->getMessage());
     }
     return $res;
 }

作者:lchsk    项目:api.lucascherkewski.co   
/**
  * Convert data to JSON and set as response, with caching header.
  *
  * @param $data mixed
  *
  * @return Response
  */
 public function buildResponse($data)
 {
     // Construct response based on provided data.
     $builtResponse = $this->response->withHeader('Content-Type', 'application/json')->write(json_encode($data, JSON_PRETTY_PRINT));
     // Return the response with an ETag added, for caching.
     return $this->c->cache->withEtag($builtResponse, sha1($builtResponse->getBody()));
 }

作者:ClearcodeH    项目:eh-library-templat   
protected function request($method, $url, array $requestParameters = [], array $headers = [])
 {
     $request = $this->prepareRequest($method, $url, $requestParameters, $headers);
     $response = new Response();
     $app = $this->app;
     $this->response = $app->callMiddlewareStack($request, $response);
     $this->jsonResponseData = json_decode((string) $this->response->getBody(), true);
 }

作者:silentwork    项目:slim-rendere   
public function render(Response $response, $template = "", $data = [])
 {
     extract($data);
     ob_start();
     include $this->templatePath . $template;
     $output = ob_get_clean();
     return $response->write($output);
 }

作者:icezlizz199    项目:tufftexgrou   
public function productRemove(Request $req, Response $res, $attr = [])
 {
     $container = $this->slim->getContainer();
     $db = $container->medoo;
     $db->delete("product", ["id" => $attr["id"]]);
     $db->delete("person_cripple", ["cripple_id" => $attr["id"]]);
     return $res->withHeader("Location", $req->getUri()->getBasePath() . "/product");
 }

作者:JohnUiterwy    项目:journey-planne   
public function writeUnauthorized()
 {
     $this->response = $this->response->withStatus(401);
     $apiResponse = new ApiResponse();
     $apiResponse->setStatusFail();
     $apiResponse->setData("Unauthorized");
     $this->body->write($apiResponse->toJSON());
 }

作者:nui    项目:gi   
public function disavantaged_typeRemove(Request $req, Response $res, $attr = [])
 {
     $container = $this->slim->getContainer();
     $db = $container->medoo;
     $db->delete("disavantaged_type", ["id" => $attr["id"]]);
     $db->delete("person_disavantaged", ["disavantaged_id" => $attr["id"]]);
     return $res->withHeader("Location", $req->getUri()->getBasePath() . "/disavantaged_type");
 }

作者:bigpoin    项目:slim-bootstra   
public function testWritePlain()
 {
     $this->_jsonTestOutputWriter->expects($this->exactly(1))->method('_jsonEncode')->with($this->equalTo(array('mockKey' => 'mockValue')))->will($this->returnValue('{"mockKey": "mockValue"}'));
     $this->_mockHeaders->expects($this->exactly(1))->method('set')->with($this->equalTo('Content-Type'), $this->equalTo('application/json; charset=UTF-8'));
     $this->_mockResponse->expects($this->exactly(1))->method('setStatus')->with($this->equalTo(200));
     $this->_mockResponse->expects($this->exactly(1))->method('setBody')->with($this->equalTo('{"mockKey": "mockValue"}'));
     $this->_jsonTestOutputWriter->writePlain(array('mockKey' => 'mockValue'));
 }

作者:cristianp    项目:slim-json-api-helpe   
/**
  * @param Response $response
  * @param int      $status
  *
  * @return ResponseInterface
  */
 public function render(Response $response, $status = 200)
 {
     // Put the default top-level members into $result object
     $result = new \StdClass();
     $result->data = $this->data;
     $result->errors = $this->errors;
     return $response->withJson($result, $status);
 }

作者:praswicakson    项目:veloc   
/**
  * @param \swoole_http_request $request
  * @param \swoole_http_response $response
  * @throws \Exception
  */
 public function __invoke($request, $response)
 {
     $this->app->getContainer()['environment'] = $this->app->getContainer()->factory(function () {
         return new Environment($_SERVER);
     });
     $this->app->getContainer()['request'] = $this->app->getContainer()->factory(function ($container) {
         return Request::createFromEnvironment($container['environment']);
     });
     $this->app->getContainer()['response'] = $this->app->getContainer()->factory(function ($container) {
         $headers = new Headers(['Content-Type' => 'text/html']);
         $response = new Response(200, $headers);
         return $response->withProtocolVersion($container->get('settings')['httpVersion']);
     });
     /**
      * @var ResponseInterface $appResponse
      */
     $appResponse = $this->app->run(true);
     // set http header
     foreach ($appResponse->getHeaders() as $key => $value) {
         $filter_header = function ($header) {
             $filtered = str_replace('-', ' ', $header);
             $filtered = ucwords($filtered);
             return str_replace(' ', '-', $filtered);
         };
         $name = $filter_header($key);
         foreach ($value as $v) {
             $response->header($name, $v);
         }
     }
     // set http status
     $response->status($appResponse->getStatusCode());
     // send response to browser
     if (!$this->isEmptyResponse($appResponse)) {
         $body = $appResponse->getBody();
         if ($body->isSeekable()) {
             $body->rewind();
         }
         $settings = $this->app->getContainer()->get('settings');
         $chunkSize = $settings['responseChunkSize'];
         $contentLength = $appResponse->getHeaderLine('Content-Length');
         if (!$contentLength) {
             $contentLength = $body->getSize();
         }
         $totalChunks = ceil($contentLength / $chunkSize);
         $lastChunkSize = $contentLength % $chunkSize;
         $currentChunk = 0;
         while (!$body->eof() && $currentChunk < $totalChunks) {
             if (++$currentChunk == $totalChunks && $lastChunkSize > 0) {
                 $chunkSize = $lastChunkSize;
             }
             $response->write($body->read($chunkSize));
             if (connection_status() != CONNECTION_NORMAL) {
                 break;
             }
         }
         $response->end();
     }
 }

作者:eella    项目:gredu_lab   
public function __invoke(Request $req, Response $res)
 {
     $result = $this->authService->authenticate();
     if (!$result->isValid()) {
         $this->flash->addMessage('danger', reset($result->getMessages()));
         return $res->withRedirect($this->loginUrl);
     }
     return $res->withRedirect($this->successUrl);
 }


问题


面经


文章

微信
公众号

扫码关注公众号