当前位置: 首页>>代码示例>>PHP>>正文


PHP Application::delete方法代码示例

本文整理汇总了PHP中Silex\Application::delete方法的典型用法代码示例。如果您正苦于以下问题:PHP Application::delete方法的具体用法?PHP Application::delete怎么用?PHP Application::delete使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Silex\Application的用法示例。


在下文中一共展示了Application::delete方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: CollectionService

    return new CollectionService($app['resource.service'], $app['triplestore'], $app['fedora']);
};
$app['collection.controller'] = function () use($app) {
    return new CollectionController($app['collection.service']);
};
$app['transaction.service'] = function () use($app) {
    return new TransactionService($app['fedora']);
};
$app['transaction.controller'] = function () use($app) {
    return new TransactionController($app['transaction.service']);
};
$app->get('islandora/resource/{id}', 'resource.controller:find');
$app->post('islandora/resource/', 'resource.controller:create');
$app->put('islandora/resource/{id}', 'resource.controller:upsert');
$app->patch('islandora/resource/{id}', 'resource.controller:sparqlUpdate');
$app->delete('islandora/resource/{id}', 'resource.controller:delete');
$app->get('islandora/transaction/{id}', 'transaction.controller:status');
$app->post('islandora/transaction/', 'transaction.controller:create');
$app->post('islandora/transaction/{id}', 'transaction.controller:extend');
$app->post('islandora/transaction/{id}/commit', 'transaction.controller:commit');
$app->post('islandora/transaction/{id}/rollback', 'transaction.controller:rollback');
//$app->get('islandora/members/{id}', 'members.controller:find');
//$app->post('islandora/members/{id}/{child_id}', 'members.controller:add');
//$app->delete('islandora/members/{id}/{child_id}', 'members.controller:remove');
//$app->patch('islandora/members/{id}/{child_id}/{destination_id}', 'members.controller:migrate');
$app->get('islandora/collection/', 'collection.controller:index');
$app->post('islandora/collection/', 'collection.controller:create');
//$app->get('islandora/files/{id}', 'files.controller:find');
//$app->post('islandora/files/{id}/{child_id}', 'files.controller:add');
//$app->delete('islandora/files/{id}/{child_id}', 'files.controller:remove');
//$app->patch('islandora/files/{id}/{child_id}/{destination_id}', 'files.controller:migrate');
开发者ID:daniel-dgi,项目名称:silexTest,代码行数:31,代码来源:index.php

示例2: Response

        return new Response('Faltam parâmetros', 400);
    }
    $sql = "SELECT * FROM cervejas WHERE nome = ?";
    $cerveja = $app['db']->fetchAssoc($sql, array($id));
    if (!$cerveja) {
        return new Response(json_encode('Não encontrada'), 404);
    }
    //Persiste na base de dados
    $app['db']->update('cervejas', array('nome' => $data['nome'], 'estilo' => $data['estilo']), array('id' => $cerveja['id']));
    return new Response('Cerveja atualizada', 200);
});
$app->delete('/cervejas/{id}', function (Request $request, $id) use($app) {
    //busca da base de dados
    $sql = "SELECT * FROM cervejas WHERE nome = ?";
    $cerveja = $app['db']->fetchAssoc($sql, array($id));
    if (!$cerveja) {
        return new Response(json_encode('Não encontrada'), 404);
    }
    $app['db']->delete('cervejas', array('id' => $cerveja['id']));
    return new Response('Cerveja removida', 200);
});
// $app->before(function (Request $request) use ($app) {
//     if( ! $request->headers->has('authorization')){
//         return new Response('Unauthorized', 401);
//     }
//     require_once 'configs/clients.php';
//     if (!in_array($request->headers->get('authorization'), array_keys($clients))) {
//         return new Response('Unauthorized', 401);
//     }
// });
$app->after(function (Request $request, Response $response) {
    $response->headers->set('Content-Type', 'text/json');
开发者ID:enieber,项目名称:restbeer,代码行数:32,代码来源:index.php

示例3: insert

    insert('dogs_race', $req->request->all());
    return $app->json(one('select * from dogs_race order by id desc limit 1'));
});
$app->get('/races/{id}', function (Application $app, Request $req, $id) {
    return $app->json(one('select * from dogs_race where id =' . q($id)));
});
$app->put('/races/{id}', function (Application $app, Request $req, $id) {
    $json = $req->request->all();
    unset($json['id']);
    update('dogs_race', $id, $json);
    return $app->json();
});
$app->options('/races/{id}', function (Application $app, Request $req, $id) {
    return new Response('', 204);
});
$app->delete('/races/{id}', function (Application $app, Request $req, $id) {
    query('delete from dogs_race where id=' . q($id));
    return new Response('', 204);
});
$app->get('/dogs', function (Application $app, Request $req) {
    $pp = (int) $req->get('_perPage');
    $p = (int) $req->get('_page') - 1;
    if ($pp == 0) {
        $pp = 30;
    }
    return $app->json(all('select * from dogs_dogs limit ' . $pp . ' offset ' . $p * $pp), 200, ['X-Total-Count' => col('select count(*) from dogs_dogs')]);
});
$app->get('/dogs/{id}', function (Application $app, Request $req, $id) {
    return $app->json(one('select * from dogs_dogs where id = ' . q($id)));
});
$app->run();
开发者ID:Bubujka,项目名称:ng-admin-learning,代码行数:31,代码来源:index.php

示例4: register

 public function register(Application $app)
 {
     $app["bbsapi.thread.management"] = function (Application $app) {
         return new ThreadManagement($app["entity_manager"]);
     };
     $app["bbsapi.thread.post_management"] = function (Application $app) {
         return new ThreadPostManagement($app["entity_manager"]);
     };
     $app["bbsapi.tag.registration"] = function (Application $app) {
         return new TagRegistration($app["entity_manager"]);
     };
     $app["bbsapi.spec.thread_spec"] = function () {
         return new ThreadSpec();
     };
     $app["bbsapi.spec.post_spec"] = function () {
         return new PostSpec();
     };
     $app["bbsapi.spec.tags_spec"] = function () {
         return new TagsSpec();
     };
     $app->post("/threads", function (Application $app, Request $req) {
         /** @var ThreadSpec $threadSpec */
         $threadSpec = $app["bbsapi.spec.thread_spec"];
         /** @var TagsSpec $tagsSpec */
         $tagsSpec = $app["bbsapi.spec.tags_spec"];
         /** @var ThreadManagement $service */
         $service = $app["bbsapi.thread.management"];
         /** @var TagRegistration $tagRegistration */
         $tagRegistration = $app["bbsapi.tag.registration"];
         $user = $req->getUser();
         if (!$user) {
             return $app->json([], 401);
         }
         $title = trim($req->request->get("title"));
         $tagNames = $req->request->get("tags");
         if (is_array($tagNames) || is_null($tagNames)) {
             $tags = new Tags($tagNames);
         } else {
             return $app->json(["errors" => ["tags" => "The tags field must be array strings."]], 400);
         }
         $thread = new Thread();
         $thread->setTitle($title);
         $threadResult = $threadSpec->validate($thread);
         $tagsResult = $tagsSpec->validate($tags);
         if (!$threadResult->isValid() || !$tagsResult->isValid()) {
             $errors = array_merge($threadResult->getErrors(), $tagsResult->getErrors());
             return $app->json(["errors" => $errors], 400);
         }
         foreach ($tags as $tag) {
             $thread->addTag($tagRegistration->register($tag));
         }
         $thread = $service->create($thread, $user);
         return $app->json($threadSpec->format($thread), 201);
     });
     $app->get("/threads/{id}", function (Application $app, $id) {
         /** @var ThreadSpec $threadSpec */
         $threadSpec = $app["bbsapi.spec.thread_spec"];
         /** @var ThreadManagement $service */
         $service = $app["bbsapi.thread.management"];
         $thread = $service->findOne($id);
         if (!$thread) {
             return $app->json([], 404);
         }
         return $app->json($threadSpec->format($thread));
     })->assert('id', '^\\d+$');
     $app->get("/threads", function (Application $app, Request $req) {
         /** @var ThreadSpec $threadSpec */
         $threadSpec = $app["bbsapi.spec.thread_spec"];
         /** @var ThreadManagement $service */
         $service = $app["bbsapi.thread.management"];
         $tags = $req->query->get("tags");
         if (is_null($tags) || $tags === "") {
             return $app->json([]);
         }
         $tags = new Tags(explode(',', $tags));
         $threads = $service->findByTags($tags);
         return $app->json(array_map(function ($thread) use($threadSpec) {
             return $threadSpec->format($thread);
         }, $threads));
     });
     $app->delete("/threads/{id}", function (Application $app, Request $req, $id) {
         /** @var ThreadManagement $service */
         $service = $app["bbsapi.thread.management"];
         $thread = $service->findOne($id);
         if (!$thread) {
             return $app->json([], 404);
         }
         $user = $req->getUser();
         if (!$user) {
             return $app->json([], 401);
         }
         $result = $service->remove($thread, $user);
         if (!$result) {
             return $app->json([], 403);
         }
         return $app->json([], 200);
     })->assert('id', '^\\d+$');
     $app->post("/threads/{id}/posts", function (Application $app, Request $req, $id) {
         /** @var ThreadManagement $threadService */
         $threadService = $app["bbsapi.thread.management"];
//.........这里部分代码省略.........
开发者ID:kumatch,项目名称:sandbox-php-bbsapi,代码行数:101,代码来源:BBSAPIThreadServiceProvider.php

示例5: createResource

 /**
  * Create a resource and all its sub-resources.
  *
  * @param array $resourceConfig
  * @param array $parentUris
  * @throws \RuntimeException
  */
 public function createResource(array $resourceConfig, array $parentUris = array())
 {
     if (empty($resourceConfig['uri']) || empty($resourceConfig['ctl'])) {
         throw new \RuntimeException('Invalid resource config encountered. Config must contain uri and ctl keys');
     }
     if ($resourceConfig['ctl'] instanceof \Closure) {
         //registers controller factory inline
         $controllerName = $this->registerController($resourceConfig['uri'], $resourceConfig['ctl'], $parentUris);
     } elseif (is_string($resourceConfig['ctl'])) {
         $controllerName = $resourceConfig['ctl'];
     } else {
         throw new \RuntimeException('Ctl must be a factory (Closure) or existing service (string name)');
     }
     //setup routes
     $this->app->get($this->createRouteUri($resourceConfig['uri'], $parentUris, true), sprintf('%s:get', $controllerName));
     $this->app->get($this->createRouteUri($resourceConfig['uri'], $parentUris, false), sprintf('%s:cget', $controllerName));
     $this->app->post($this->createRouteUri($resourceConfig['uri'], $parentUris, false), sprintf('%s:post', $controllerName));
     $this->app->put($this->createRouteUri($resourceConfig['uri'], $parentUris, true), sprintf('%s:put', $controllerName));
     $this->app->patch($this->createRouteUri($resourceConfig['uri'], $parentUris, true), sprintf('%s:patch', $controllerName));
     $this->app->delete($this->createRouteUri($resourceConfig['uri'], $parentUris, true), sprintf('%s:delete', $controllerName));
     //handle sub resources
     if (!empty($resourceConfig['sub'])) {
         if (!is_array($resourceConfig['sub'])) {
             throw new \RuntimeException('sub config must contain array of sub resources');
         }
         //append current uri as parent
         $parentUris[] = $resourceConfig['uri'];
         foreach ($resourceConfig['sub'] as $subResource) {
             $this->createResource($subResource, $parentUris);
         }
     }
 }
开发者ID:warmans,项目名称:silex-rest-provider,代码行数:39,代码来源:RestService.php

示例6: loadDelete

 private function loadDelete()
 {
     $this->application->delete('/api/' . $this->version . '/address-books/{id}.json', function (Application $application, $id) {
         $controller = new AddressBook($application);
         return $controller->delete($id);
     })->convert('id', function ($id) {
         return (int) $id;
     })->assert('id', '\\d+');
 }
开发者ID:bflechel,项目名称:OpenAddressBook,代码行数:9,代码来源:Dispatcher.php

示例7: register

 /**
  * {@inheritDoc}
  */
 public function register(SilexApplication $app)
 {
     $app['payum.api.controller.root'] = $app->share(function () {
         return new RootController();
     });
     $app['payum.api.controller.payment'] = $app->share(function () use($app) {
         return new PaymentController($app['payum.security.token_factory'], $app['payum.security.http_request_verifier'], $app['payum'], $app['api.view.order_to_json_converter'], $app['form.factory'], $app['api.view.form_to_json_converter']);
     });
     $app['payum.api.controller.gateway'] = $app->share(function () use($app) {
         return new GatewayController($app['form.factory'], $app['url_generator'], $app['api.view.form_to_json_converter'], $app['payum.gateway_config_storage'], $app['api.view.gateway_config_to_json_converter']);
     });
     $app['payum.api.controller.gateway_meta'] = $app->share(function () use($app) {
         return new GatewayMetaController($app['form.factory'], $app['api.view.form_to_json_converter'], $app['payum']);
     });
     $app->get('/', 'payum.api.controller.root:rootAction')->bind('api_root');
     $app->get('/payments/meta', 'payum.api.controller.payment:metaAction')->bind('payment_meta');
     $app->get('/payments/{payum_token}', 'payum.api.controller.payment:getAction')->bind('payment_get');
     $app->put('/payments/{payum_token}', 'payum.api.controller.payment:updateAction')->bind('payment_update');
     $app->delete('/payments/{payum_token}', 'payum.api.controller.payment:deleteAction')->bind('payment_delete');
     $app->post('/payments', 'payum.api.controller.payment:createAction')->bind('payment_create');
     $app->get('/payments', 'payum.api.controller.payment:allAction')->bind('payment_all');
     $app->get('/gateways/meta', 'payum.api.controller.gateway_meta:getAllAction')->bind('payment_factory_get_all');
     $app->get('/gateways', 'payum.api.controller.gateway:allAction')->bind('gateway_all');
     $app->get('/gateways/{name}', 'payum.api.controller.gateway:getAction')->bind('gateway_get');
     $app->delete('/gateways/{name}', 'payum.api.controller.gateway:deleteAction')->bind('gateway_delete');
     $app->post('/gateways', 'payum.api.controller.gateway:createAction')->bind('gateway_create');
     $app->before(function (Request $request, Application $app) {
         if (in_array($request->getMethod(), array('GET', 'OPTIONS', 'DELETE'))) {
             return;
         }
         if ('json' !== $request->getContentType()) {
             throw new BadRequestHttpException('The request content type is invalid. It must be application/json');
         }
         $decodedContent = json_decode($request->getContent(), true);
         if (null === $decodedContent) {
             throw new BadRequestHttpException('The request content is not valid json.');
         }
         $request->attributes->set('content', $decodedContent);
     });
     $app->after(function (Request $request, Response $response) use($app) {
         if ($response instanceof JsonResponse && $app['debug']) {
             $response->setEncodingOptions($response->getEncodingOptions() | JSON_PRETTY_PRINT);
         }
     });
     $app->after($app["cors"]);
     $app->error(function (\Exception $e, $code) use($app) {
         if ('json' !== $app['request']->getContentType()) {
             return;
         }
         return new JsonResponse(array('exception' => get_class($e), 'message' => $e->getMessage(), 'code' => $e->getCode(), 'file' => $e->getFile(), 'line' => $e->getLine(), 'stackTrace' => $e->getTraceAsString()));
     }, $priority = -100);
 }
开发者ID:Headd2k,项目名称:PayumServer,代码行数:55,代码来源:ApiControllerProvider.php

示例8: register

 public function register(BaseApplication $app)
 {
     // 定休日テーブル用リポジトリ
     $app['eccube.plugin.holiday.repository.holiday'] = $app->share(function () use($app) {
         return $app['orm.em']->getRepository('Plugin\\Holiday\\Entity\\Holiday');
     });
     $basePath = '/' . $app["config"]["admin_route"];
     // 一覧
     $app->match($basePath . '/system/shop/holiday/', '\\Plugin\\Holiday\\Controller\\HolidayController::index')->bind('admin_setting_shop_holiday');
     // 新規作成
     $app->match($basePath . '/system/shop/holiday/new', '\\Plugin\\Holiday\\Controller\\HolidayController::edit')->bind('admin_setting_shop_holiday_new');
     // 編集
     $app->match($basePath . '/system/shop/holiday/{id}/edit', '\\Plugin\\Holiday\\Controller\\HolidayController::edit')->assert('id', '\\d+')->bind('admin_setting_shop_holiday_edit');
     // 一覧:削除
     $app->delete($basePath . '/system/shop/holiday/{id}/delete', '\\Plugin\\Holiday\\Controller\\HolidayController::delete')->assert('id', '\\d+')->bind('admin_setting_shop_holiday_delete');
     // 一覧:上
     $app->put($basePath . '/system/shop/holiday/{id}/up', '\\Plugin\\Holiday\\Controller\\HolidayController::up')->assert('id', '\\d+')->bind('admin_setting_shop_holiday_up');
     // 一覧:下
     $app->put($basePath . '/system/shop/holiday/{id}/down', '\\Plugin\\Holiday\\Controller\\HolidayController::down')->assert('id', '\\d+')->bind('admin_setting_shop_holiday_down');
     $app->match('/block/holiday_calendar_block', '\\Plugin\\Holiday\\Controller\\Block\\HolidayController::index')->bind('block_holiday_calendar_block');
     // 型登録
     $app['form.types'] = $app->share($app->extend('form.types', function ($types) use($app) {
         $types[] = new \Plugin\Holiday\Form\Type\HolidayType($app);
         return $types;
     }));
     // メッセージ登録
     $app['translator'] = $app->share($app->extend('translator', function ($translator, \Silex\Application $app) {
         $translator->addLoader('yaml', new \Symfony\Component\Translation\Loader\YamlFileLoader());
         $file = __DIR__ . '/../Resource/locale/message.' . $app['locale'] . '.yml';
         if (file_exists($file)) {
             $translator->addResource('yaml', $file, $app['locale']);
         }
         return $translator;
     }));
     // load config
     $conf = $app['config'];
     $app['config'] = $app->share(function () use($conf) {
         $confarray = array();
         $path_file = __DIR__ . '/../Resource/config/path.yml';
         if (file_exists($path_file)) {
             $config_yml = Yaml::parse(file_get_contents($path_file));
             if (isset($config_yml)) {
                 $confarray = array_replace_recursive($confarray, $config_yml);
             }
         }
         return array_replace_recursive($conf, $confarray);
     });
     // メニュー登録
     $app['config'] = $app->share($app->extend('config', function ($config) {
         $addNavi['id'] = "holiday";
         $addNavi['name'] = "定休日管理";
         $addNavi['url'] = "admin_setting_shop_holiday";
         self::addNavi($config['nav'], $addNavi, array('setting', 'shop'));
         return $config;
     }));
 }
开发者ID:ActiveFusions,项目名称:Holiday-plugin,代码行数:56,代码来源:HolidayServiceProvider.php

示例9: testMatchReturnValue

 public function testMatchReturnValue()
 {
     $app = new Application();
     $returnValue = $app->match('/foo', function () {
     });
     $this->assertInstanceOf('Silex\\Controller', $returnValue);
     $returnValue = $app->get('/foo', function () {
     });
     $this->assertInstanceOf('Silex\\Controller', $returnValue);
     $returnValue = $app->post('/foo', function () {
     });
     $this->assertInstanceOf('Silex\\Controller', $returnValue);
     $returnValue = $app->put('/foo', function () {
     });
     $this->assertInstanceOf('Silex\\Controller', $returnValue);
     $returnValue = $app->delete('/foo', function () {
     });
     $this->assertInstanceOf('Silex\\Controller', $returnValue);
 }
开发者ID:nicodmf,项目名称:Silex,代码行数:19,代码来源:ApplicationTest.php

示例10: register

 public function register(Application $app, $uri)
 {
     $resource = $this->get($uri);
     $metadata = $resource->getMetadata();
     $base = '/' . $uri;
     if (is_callable(array($resource, 'get'))) {
         $app->get($base, 'controller.resourcehub:get')->bind($uri . ':list');
     }
     if (is_callable(array($resource, 'getOne'))) {
         $app->get($base . '/{id}', 'controller.resourcehub:get')->bind($uri . ':get');
     }
     if (is_callable(array($resource, 'post'))) {
         $app->post($base . '/{id}', 'controller.resourcehub:post')->bind($uri . ':post');
     }
     if (is_callable(array($resource, 'put'))) {
         $app->put($base, 'controller.resourcehub:put')->bind($uri . ':put');
     }
     if (is_callable(array($resource, 'delete'))) {
         $app->delete($base . '/{id}', 'controller.resourcehub:delete')->bind($uri . ':delete');
     }
 }
开发者ID:mcuadros,项目名称:silex-hateoas,代码行数:21,代码来源:ResourceHub.php

示例11: constructPublicRoutes

 /**
  * Builds the routes that can be accesses all the time without being logged in.
  *
  * @param Application $app
  */
 private function constructPublicRoutes(Application $app)
 {
     // Home
     $app->get('/v1/', 'WineTasting\\Controller\\HomeController::info');
     // User
     $app->post('/v1/user/register', 'WineTasting\\Controller\\UserController::register');
     $app->get('/v1/user/{id}/votes', 'WineTasting\\Controller\\UserController::getVotes');
     $app->get('/v1/user/{id}/tasted', 'WineTasting\\Controller\\UserController::getTasted');
     $app->post('/v1/user/{id}/tasted/{idWine}', 'WineTasting\\Controller\\UserController::addTasted');
     $app->delete('/v1/user/{id}/tasted/{idWine}', 'WineTasting\\Controller\\UserController::removeTasted');
     // Wine
     $app->get('/v1/wine', 'WineTasting\\Controller\\WineController::getWines');
     $app->get('/v1/wine/ranking', 'WineTasting\\Controller\\WineController::getRankedWines');
     $app->get('/v1/wine/{id}', 'WineTasting\\Controller\\WineController::getWine');
     $app->post('/v1/wine', 'WineTasting\\Controller\\WineController::create');
     $app->post('/v1/wine/vote1', 'WineTasting\\Controller\\WineController::vote1');
     $app->post('/v1/wine/vote2', 'WineTasting\\Controller\\WineController::vote2');
     $app->post('/v1/wine/vote3', 'WineTasting\\Controller\\WineController::vote3');
     // Config
     $app->post('/v1/config/{name}', 'WineTasting\\Controller\\ConfigController::setValue');
     $app->get('/v1/config/{name}', 'WineTasting\\Controller\\ConfigController::getValue');
 }
开发者ID:sebastianhaeni,项目名称:wine-tasting,代码行数:27,代码来源:Router.php

示例12: register

 public function register(BaseApplication $app)
 {
     // 管理画面:一覧
     $app->match('/' . $app['config']['admin_route'] . '/plugin/uzaitaikai/config', 'Plugin\\Uzaitaikai\\Controller\\ConfigController::index')->bind('plugin_Uzaitaikai_config');
     // 管理画面:新規登録
     $app->match('/' . $app['config']['admin_route'] . '/plugin/uzaitaikai/config/new', 'Plugin\\Uzaitaikai\\Controller\\ConfigController::edit')->bind('plugin_Uzaitaikai_config_new');
     // 管理画面:編集
     $app->match('/' . $app['config']['admin_route'] . '/plugin/uzaitaikai/config/{id}/edit', 'Plugin\\Uzaitaikai\\Controller\\ConfigController::edit')->assert('id', '\\d+')->bind('plugin_Uzaitaikai_config_edit');
     // 管理画面:削除
     $app->delete('/' . $app['config']['admin_route'] . '/plugin/uzaitaikai/config/{id}/delete', 'Plugin\\Uzaitaikai\\Controller\\ConfigController::delete')->assert('id', '\\d+')->bind('plugin_Uzaitaikai_config_delete');
     // マイページ:退会画面 ※本体のルーティングを上書き.
     $app->match('/mypage/withdraw', 'Plugin\\Uzaitaikai\\Controller\\WithdrawController::index')->bind('mypage_withdraw');
     // Repository
     $app['plugin.Uzaitaikai.repository.question'] = $app->share(function () use($app) {
         return $app['orm.em']->getRepository('Plugin\\Uzaitaikai\\Entity\\Question');
     });
     // Form
     $app['form.types'] = $app->share($app->extend('form.types', function ($types) use($app) {
         $types[] = new Mypage\QuestionType($app);
         $types[] = new Admin\QuestionType($app);
         return $types;
     }));
 }
开发者ID:chihiro-adachi,项目名称:eccube3-uzaitaikai-plugin,代码行数:23,代码来源:UzaitaikaiServiceProvider.php

示例13: connect

 public function connect(Application $app)
 {
     $controllers = new ControllerCollection($app['route_factory']);
     $app->get('/users/', function () use($app) {
         /** @var $request \Symfony\Component\HttpFoundation\Request */
         $request = $app['request'];
         $rows = (int) $request->get('rows', 10);
         $offset = (int) $request->get('offset', 0);
         /** @var $em \Doctrine\ORM\EntityManager */
         //@todo refactor to use repo
         $em = $app['doctrine_orm.em'];
         $query = $em->createQuery('SELECT u.surname, u.lastname, u.email, u.birthdate, u.name
             FROM Bibi\\Entity\\User u
          ');
         $query->setMaxResults($rows);
         $query->setFirstResult($offset);
         $result = $query->getResult();
         return $app->json($result);
     })->bind('users.index');
     $app->get('/users/{id}', function ($id) use($app) {
         /** @var $em \Doctrine\ORM\EntityManager */
         $em = $app['doctrine_orm.em'];
         $user = $em->getRepository("Bibi\\Entity\\User");
         $result = $user->findOneById($id);
         $data = new \stdClass();
         $status = 500;
         if (!empty($result)) {
             $data->users = array($result->getSimpleObject());
             $status = 200;
         } else {
             $data->messageId = "user.notfound";
             $status = 404;
         }
         return $app->json($data, $status);
     })->bind('user.id')->convert('id', function ($id) {
         return (int) $id;
     });
     $app->post('/users/', function () use($app) {
         /** @var $request \Symfony\Component\HttpFoundation\Request */
         $request = $app['request'];
         $requestData = json_decode($request->get('data', ""));
         $data = new \stdClass();
         $status = 500;
         $headers = array();
         if (!empty($requestData)) {
             /** @var $validator Symfony\Component\Validator\Validator*/
             $validator = $app['validator'];
             $errors = $validator->validate($requestData);
             if (count($errors) > 0) {
                 $data->messageId = "user.datainvalid";
                 $status = 404;
             } else {
                 /** @var $em \Doctrine\ORM\EntityManager */
                 $em = $app['doctrine_orm.em'];
                 /** @var $userRepo \Bibi\Repo\UserRepo */
                 $userRepo = $em->getRepository("Bibi\\Entity\\User");
                 /** @var $result \Bibi\Entity\User */
                 $result = $userRepo->findOneByName($requestData->name);
                 if (empty($result)) {
                     $user = new \Bibi\Entity\User();
                     foreach (get_object_vars($requestData) as $attr => $value) {
                         $methodName = "set" . ucfirst($attr);
                         call_user_func_array(array($user, $methodName), array($value));
                     }
                     $em->persist($user);
                     $em->flush();
                     $url = $app['url_generator']->generate('user.id', array("id" => $user->getId()));
                     $status = 201;
                 } else {
                     $url = $app['url_generator']->generate('user.id', array("id" => $result->getId()));
                     $data->messageId = "user.exists";
                     $status = 303;
                 }
                 $headers = array("Location" => $url);
             }
         } else {
             $data->messageId = "user.datainvalid";
             $status = 404;
         }
         return $app->json($data, $status, $headers);
     })->bind('user.add');
     $app->delete('/users/{id}', function ($id) use($app) {
         /** @var $em \Doctrine\ORM\EntityManager */
         $em = $app['doctrine_orm.em'];
         /** @var $userRepo \Bibi\Repo\UserRepo */
         $userRepo = $em->getRepository("Bibi\\Entity\\User");
         /** @var $result \Bibi\Entity\User */
         $result = $userRepo->findOneById((int) $id);
         $status = 500;
         $data = new \stdClass();
         if (empty($result)) {
             $status = 410;
             $data->messageId = 'user.notexists';
         } else {
             $em->remove($result);
             $em->flush();
             $status = 200;
             $data->messageId = 'user.removed';
         }
         return $app->json($data, $status);
//.........这里部分代码省略.........
开发者ID:newLoki,项目名称:Bibi,代码行数:101,代码来源:UserControllerProvider.php

示例14: array

    $idEstado = $request->request->get('idEstado');
    $r = 0;
    if ($id) {
        $sql = "UPDATE Cidades SET nome = ?, idEstado = ? WHERE id = ?";
        $r = $db->executeUpdate($sql, array($nome, $idEstado, $id));
    } else {
        $sql = "INSERT INTO Cidades(nome, idEstado) VALUES(?, ?)";
        $db->executeUpdate($sql, array($nome, $idEstado));
        $r = $db->lastInsertId();
    }
    return $r;
});
// exclui uma cidade
$app->delete('/cidades/{id}', function ($id) use($app, $db) {
    $sql = "DELETE FROM Cidades WHERE id = ?";
    $r = $db->executeUpdate($sql, array($id));
    return $r;
});
// estados
// retorna a lista de estados
$app->get('/estados', function () use($app, $db) {
    $sql = "SELECT * FROM Estados ORDER BY nome";
    $query = $db->executeQuery($sql);
    $estados = $query->fetchAll();
    return $app->json($estados);
});
// retorna um estado específico, com base no id (parâmetro de rota)
$app->get('/estados/{id}', function ($id) use($app, $db) {
    $sql = "SELECT * FROM Estados WHERE id = ? ORDER BY nome";
    $query = $db->executeQuery($sql, array($id));
    $estado = $query->fetch();
开发者ID:jacksongomesbr,项目名称:livro-web-codigo-fonte,代码行数:31,代码来源:index.php

示例15: storage_file_name

}
function storage_file_name(Request $request, $name)
{
    return __DIR__ . '/../../../../state/' . $name . '-' . $request->server->get('SERVER_PORT');
}
function clear(Request $request, $name)
{
    $fileName = storage_file_name($request, $name);
    if (file_exists($fileName)) {
        unlink($fileName);
    }
}
$app = new Application();
$app['debug'] = true;
$app->delete('/_expectation', static function (Request $request) {
    clear($request, 'expectations');
    return new Response('', 200);
});
$app->post('/_expectation', static function (Request $request) {
    $matcher = [];
    if ($request->request->has('matcher')) {
        $matcher = silent_deserialize($request->request->get('matcher'));
        $validator = static function ($closure) {
            return is_callable($closure);
        };
        if (!is_array($matcher) || count(array_filter($matcher, $validator)) !== count($matcher)) {
            return new Response('POST data key "matcher" must be a serialized list of closures', 417);
        }
    }
    if (!$request->request->has('response')) {
        return new Response('POST data key "response" not found in POST data', 417);
    }
开发者ID:colindecarlo,项目名称:http-mock,代码行数:32,代码来源:app.php


注:本文中的Silex\Application::delete方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。