示例#1
8
<?php

use Phalcon\Mvc\Micro;
use Phalcon\Http\Response;
use Phalcon\Loader;
use Phalcon\DI\FactoryDefault;
use Phalcon\Db\Adapter\Pdo\Mysql as PdoMysql;
$loader = new Loader();
$loader->registerDirs(array(__DIR__ . '/models/'))->register();
$di = new FactoryDefault();
$di->set('db', function () {
    return new PdoMysql(array("host" => "localhost", "username" => "root", "password" => "", "dbname" => "classicmodels"));
});
$app = new Micro($di);
$app->get('/', function () {
    $response = new Response();
    $response->setContent('<h1 style="text-align:center">Sorry, the page doesn\'t exist</h1>');
    $response->send();
});
$app->get('/api/customers/top/{year}', function ($year) use($app) {
    $phql = "SELECT customers.customerNumber,customers.contactLastName, customers.contactFirstName, customers.customerName,SUM(orderdetails.quantityOrdered) FROM orders \n\t\t\t\t\t INNER JOIN customers on customers.customerNumber = orders.customerNumber\n\t\t\t\t\t INNER JOIN orderdetails on orderdetails.orderNumber = orders.orderNumber\n\t\t\t\t\t WHERE orders.orderDate BETWEEN :startDate: AND :endDate:\n\t\t\t\t\t AND orderdetails.quantityOrdered GROUP BY customers.customerNumber\n\t\t\t\t\t ORDER BY SUM(orderdetails.quantityOrdered) DESC LIMIT 5  ";
    $result = $app->modelsManager->executeQuery($phql, array('startDate' => $year . '-01-01', 'endDate' => $year . '-12-12'));
    $data = array();
    foreach ($result as $customer) {
        $data[] = array('id' => utf8_encode($customer->customerNumber), 'name' => utf8_encode($customer->customerName), 'contact_lname' => utf8_encode($customer->contactLastName), 'contact_fname' => utf8_encode($customer->contactFirstName));
    }
    echo json_encode($data);
});
$app->get('/api/productline/top/{productLine}', function ($productLine) use($app) {
    $phql = "\n\t\t\t SELECT orderdetails.productCode,products.productName,products.productLine,products.buyPrice, SUM(orderdetails.quantityOrdered) \n\t\t\t FROM orderdetails \n\t\t\t INNER JOIN products on products.productCode = orderdetails.productCode \n\t\t\t INNER JOIN orders on orders.orderNumber = orderdetails.orderNumber \n\t\t\t WHERE orders.orderDate BETWEEN '2003-01-01' AND '2005-12-12' AND products.productLine = :productLine:\n\t\t\t GROUP BY orderdetails.productCode ORDER BY SUM(orderdetails.quantityOrdered) DESC LIMIT 5";
    $results = $app->modelsManager->executeQuery($phql, array('productLine' => $productLine));
示例#2
0
 public function execMicro()
 {
     $di = new FactoryDefault();
     $application = new Micro();
     $application->setDI($di);
     $this->load(APP_ROOT . 'apps/config/loadermicro.php', $di);
     return $application;
 }
示例#3
0
 private function setNotFoundAction()
 {
     $app = $this->app;
     $this->app->notFound(function () use($app) {
         $logger = new Logger();
         $content = "Invalid url called [" . $app->request->getMethod() . "]" . $app->request->getURI();
         $logger->error($content);
         $app->response->setStatusCode(404, "Not Found")->sendHeaders();
         Debug::output($content);
     });
 }
示例#4
0
 /**
  * apps以下のrouting設定に沿ってルーティングをする
  */
 public function routing()
 {
     $nameSpace = APPS_MAIN_CONF['base_namespace'] . '\\Controllers\\';
     foreach ($this->conf as $controller => $settings) {
         $class = $nameSpace . $controller . 'Controller';
         $this->init();
         $this->router->setHandler($class, true);
         $this->router->setPrefix($settings['prefix']);
         foreach ($settings['actions'] as $method => $actions) {
             $this->setAction($method, $actions);
         }
         $this->app->mount($this->router);
     }
 }
示例#5
0
 /**
  * In phalcon, the availability of parameters in MICRO
  * applications events is not the same as the availability in regular
  * applications.
  * We have no easy way to access the controller name in the
  * beforeExecute event.
  * This is a hack that allows us to extract it, so we know which
  * controller class we are dispatching to.
  * @return strin|null
  **/
 private function extractDispatchInformation(Micro $app)
 {
     $controllerName = null;
     $actionName = null;
     $handler = $app->getActiveHandler();
     if (isset($handler[0]) && $handler[0] instanceof \Phalcon\Mvc\Micro\LazyLoader) {
         $reflector = new \ReflectionProperty($handler[0], '_definition');
         $reflector->setAccessible(true);
         $controllerName = $reflector->getValue($handler[0]);
     }
     if (isset($handler[1])) {
         $actionName = $handler[1];
     }
     return [$controllerName, $actionName];
 }
 /**
  * Mount all collections
  */
 public function mount()
 {
     $this->scanNamespaces();
     foreach ($this->collections as $col) {
         $this->app->mount($col);
     }
 }
示例#7
0
文件: App.php 项目: ovide/phest
 /**
  * Constructs the app.
  *
  * Checks singleton instance
  * Adds a dependency injector if none provided
  * Sets the notFound handler
  *
  * @param  FactoryDefault    $dependencyInjector
  * @throws \RuntimeException
  */
 public function __construct($dependencyInjector = null)
 {
     if (self::$app === null) {
         if ($dependencyInjector === null) {
             $dependencyInjector = new FactoryDefault();
         }
         $dependencyInjector->setShared('response', Response::class);
         $dependencyInjector->setShared('router', Router::class);
         if (!$dependencyInjector->has('eventsManager')) {
             $dependencyInjector->setShared('eventsManager', \Phalcon\Events\Manager::class);
         }
         if (!$dependencyInjector->has('request')) {
             $dependencyInjector->setShared('request', \Phalcon\Http\Request::class);
         }
         parent::__construct($dependencyInjector);
         self::$app = $this;
         $this->setEventsManager($dependencyInjector->getShared('eventsManager'));
         $this->addHeaderHandler(new HeaderHandler\Accept());
         $app = self::$app;
         $this->_errorHandler = function (\Exception $ex) {
             return $this->errorHandler($ex);
         };
         $this->_notFoundHandler = function () {
             return $this->notFoundHandler();
         };
     } else {
         throw new \RuntimeException("Can't instance App more than once");
     }
 }
示例#8
0
 public function beforeExecuteRoute(Event $event, Micro $app)
 {
     $role = $this->authManager->loggedIn() ? self::ROLE_PRIVATE : self::ROLE_PUBLIC;
     // Get the current resource/endpoint from the micro app
     $endpoint = $app->getRouter()->getMatchedRoute()->getPattern();
     // Get the access control list
     $acl = $this->_getAcl();
     // See if they have permission
     $allowed = $acl->isAllowed($role, self::RESOURCE_API, $endpoint);
     if ($allowed != \Phalcon\Acl::ALLOW) {
         if ($this->authManager->loggedIn()) {
             throw new UserException(ErrorCodes::AUTH_FORBIDDEN);
         } else {
             throw new UserException(ErrorCodes::AUTH_UNAUTHORIZED);
         }
     }
 }
示例#9
0
 public function handle($uri = null)
 {
     if ($this->apibird->corsEnabled()) {
         $this->options('^(/.*)$', function () {
             return '';
         });
     }
     return parent::handle($uri);
 }
示例#10
0
 /**
  * Wrapper setting the format to all listeners implementing the
  * ResponseMutatorInterface
  * @param string
  **/
 public function setResponseFormat($format = ResponseMutatorInterface::JSON)
 {
     foreach ($this->app->getEventsManager()->getListeners('micro:afterHandleRoute') as $listener) {
         if ($listener instanceof ResponseMutatorInterface) {
             $listener->setResponseFormat($format);
         }
     }
     return true;
 }
示例#11
0
use Phalcon\Loader;
use Phalcon\Db\Adapter\Pdo\Mysql as MysqlAdapter;
use Phalcon\Config\Adapter\Ini as ConfigIni;
use Phalcon\Mvc\Micro\Collection as MicroCollection;
// Setup loader
$loader = new Loader();
$loader->registerDirs(array(__DIR__ . '/app/models/', __DIR__ . '/app/controllers/', __DIR__ . '/library/'))->register();
// Read the configuration
$config = new ConfigIni(__DIR__ . '/config/config.ini');
//Start DI
$di = new FactoryDefault();
$di->set('redis', function () {
    return new RedisTest();
}, true);
// Start Micro
$app = new Micro();
$app->setDI($di);
// Setup the database service
$app['db'] = function () use($config) {
    return new MysqlAdapter(array("host" => $config->database->host, "username" => $config->database->username, "password" => $config->database->password, "dbname" => $config->database->dbname, "charset" => $config->database->charset));
};
// Include controllers
$app['controllers'] = function () {
    return ['core' => true, 'user' => true, 'messages' => true];
};
// Authentication
//$app['auth'] = function() use ($app, $config) {
//    $auth = array();
//    $authorization = $app->request->getHeader("AUTHORIZATION");
//    if ($authorization) {
//        $cut = str_replace('Basic ', '', $authorization);
示例#12
0
//Run config.php
require __DIR__ . '/config/config.php';
// Start the session the first time when some component request the session service
$di->setShared('session', function () {
    $session = new Session();
    $session->start();
    return $session;
});
//Set shared Facebook SDK
$di->setShared('facebook', function () {
    return new Facebook\Facebook(['app_id' => '976309079106997', 'app_secret' => '3d08707832a17ab10369f4f0643618aa', 'default_graph_version' => 'v2.4']);
});
//Set request object
$di->set("request", "Phalcon\\Http\\Request", true);
//Instantiate Phalcon Micro framework
$app = new Micro();
$app->setDI($di);
//Create response object
$response = new Response();
/**
 * Get random image
 */
$app->get('/images/random', function () use($app, $response) {
    $manager = $app->getDI()->get('modelsManager');
    $minMax = $manager->createBuilder()->from('Images')->columns('min(id) as minimum, max(id) as maximum')->getQuery()->getSingleResult();
    $id = rand($minMax->minimum, $minMax->maximum);
    $image = new Images();
    $response->setJsonContent($image->getImageInfo($id));
    $response->send();
});
/**
示例#13
0
文件: index.php 项目: nayed/phalcapi
use Phalcon\Loader;
use Phalcon\Mvc\Micro;
use Phalcon\Http\Response;
use Phalcon\DI\FactoryDefault;
use Phalcon\Db\Adapter\Pdo\Mysql as PdoMysql;
// use Loader() to autoload our model
$loader = new Loader();
$loader->registerDirs(array(__DIR__ . '/models/'))->register();
$di = new FactoryDefault();
// Set up the database service
$di->set('db', function () {
    return new PdoMysql(array("host" => "127.0.0.1", "username" => "root", "password" => "0000", "dbname" => "phalcapi"));
});
// Create and bind the DI to the application
$app = new Micro($di);
// Define the routes
// Retrieves all robots
$app->get('/api/robots', function () use($app) {
    $phql = "SELECT * FROM Robots ORDER BY name";
    $robots = $app->modelsManager->executeQuery($phql);
    $data = array();
    foreach ($robots as $robot) {
        $data[] = array('id' => $robot->id, 'name' => $robot->name);
    }
    echo json_encode($data);
});
// Searches for robots with $name in their name
$app->get('/api/robots/search/{name}', function ($name) use($app) {
    $phql = "SELECT * FROM Robots WHERE name LIKE :name: ORDER BY name";
    $robots = $app->modelsManager->executeQuery($phql, array('name' => '%' . $name . '%'));
示例#14
0
 public function __construct($dependencyInjector = null)
 {
     parent::__construct($dependencyInjector);
     ini_set('session.use_cookies', 0);
 }
<?php

use Phalcon\Loader;
use Phalcon\Mvc\Micro;
use Phalcon\Di\FactoryDefault;
use Phalcon\Db\Adapter\Pdo\Mysql as PdoMysql;
// Use Loader() to autoload our model
$loader = new Loader();
// Register some namespaces
$loader->registerNamespaces(array("Models" => __DIR__ . '/../app/models', "Controllers" => __DIR__ . '/../app/controllers'));
$loader->register();
$di = new FactoryDefault();
// Set up the database service
$di->set('db', function () {
    return new PdoMysql(array("host" => "localhost", "username" => "root", "password" => "123mudar", "dbname" => "ecommerce_order"));
});
// Create and bind the DI to the application
$app = new Micro($di);
// Retrieves all orders
$indexController = new \Controllers\IndexController();
$app->get('/api/orders', array($indexController, "indexAction"));
$app->handle();
示例#16
0
try {
    /**
     * Read the configuration
     */
    $config = (include __DIR__ . "/../config/config.php");
    /**
     * Include Services
     */
    include APP_PATH . '/config/services.php';
    /**
     * Include Autoloader
     */
    include APP_PATH . '/config/loader.php';
    /**
     * Starting the application
     * Assign service locator to the application
     */
    $app = new Micro($di);
    /**
     * Include Application
     */
    include APP_PATH . '/app.php';
    include APP_PATH . '/users.php';
    include APP_PATH . '/todoEntries.php';
    /**
     * Handle the request
     */
    $app->handle();
} catch (\Exception $e) {
    echo $e->getMessage();
}
示例#17
0
文件: index.php 项目: boiler256/mvc
<?php

use Phalcon\Mvc\Micro;
$app = new Micro();
$app->get('/', function () {
    echo "<h1>Welcome!</h1>";
});
$app->get('/say/hello/{name}', function ($name) use($app) {
    echo "<h1>Hello! {$name}</h1>";
    echo "Your IP Address is ", $app->request->getClientAddress();
});
$app->post('/store/something', function () use($app) {
    $name = $app->request->getPost('name');
    echo "<h1>Hello! {$name}</h1>";
});
$app->notFound(function () use($app) {
    $app->response->setStatusCode(404, "Not Found")->sendHeaders();
    echo 'This is crazy, but this page was not found!';
});
$app->handle();
示例#18
0
// use Loader() to autoload our model
$loader = new Loader();
$loader->setExtensions(array("php"));
$loader->registerDirs(array(__DIR__ . '/models/'))->register();
// set up the database service
$di = new FactoryDefault();
//----------------------------
//DATABASE CONFIG
//----------------------------
$di->set('db', function () {
    return new PdoMysql(array("host" => "localhost", "port" => "", "username" => "root", "password" => "faraz", "dbname" => "products"));
});
//table name in schema is Products, if change is made to this table name then
//API method handlers should be updated
// bind the DI to the application
$app = new Micro($di);
// API -------------------------------------------
// Products is the table name in MySQL database
// Retrieves all products
$app->get('/api/products', function () use($app) {
    $phql = "SELECT * FROM Products ORDER BY name";
    //Products is table name
    $products = $app->modelsManager->executeQuery($phql);
    $data = array();
    foreach ($products as $product) {
        $data[] = array('id' => $product->id, 'name' => $product->name, 'price' => $product->price, 'in_stock' => $product->in_stock);
    }
    echo json_encode($data);
});
// Retrieves products based on primary key
$app->get('/api/products/{id:[0-9]+}', function ($id) use($app) {
示例#19
0
<?php

use Phalcon\Mvc\Micro, Phalcon\Events\Manager as EventsManager;
//Create a events manager
$eventManager = new EventsManager();
//Listen all the application events
$eventManager->attach('micro', function ($event, $app) {
    if ($event->getType() == 'beforeExecuteRoute') {
        if ($app->session->get('auth') == false) {
            $app->flashSession->error("The user isn't authenticated");
            $app->response->redirect("/");
            //Return (false) stop the operation
            return false;
        }
    }
});
$app = new Micro();
//Bind the events manager to the app
$app->setEventsManager($eventManager);
示例#20
0
 public function testMicroStopMiddlewareClasses()
 {
     $this->specify("Micro middleware events don't work as expected", function () {
         $app = new Micro();
         $app->map("/api/site", function () {
             return true;
         });
         $middleware = new \MyMiddlewareStop();
         $app->before($middleware);
         $app->before($middleware);
         $app->after($middleware);
         $app->after($middleware);
         $app->finish($middleware);
         $app->finish($middleware);
         $app->handle("/api/site");
         expect($middleware->getNumber())->equals(3);
     });
 }
示例#21
0
文件: index.php 项目: boiler256/mvc
<?php

use Phalcon\Mvc\Micro;
use Phalcon\Http\Response;
require "config/config.php";
require "config/services.php";
$app = new Micro($di);
$app->get('/', function () use($app) {
    echo $app['view']->render('index');
});
$app->notFound(function () use($app) {
    echo $app['view']->render('404');
});
$app->error(function () use($app) {
    echo $app['view']->render('500');
});
$app->handle();
示例#22
0
<?php

use Phalcon\Mvc\Micro;
use Phalcon\DI\FactoryDefault;
use Phalcon\Mvc\Url;
$app = new Micro();
$di = new FactoryDefault();
$di->set('url', function () {
    $url = new Url();
    $url->setBaseUri('/');
    return $url;
}, true);
$app->setDi($di);
$app->response->setContentType('application/json', 'UTF-8');
require_once __DIR__ . '/routes.php';
$app->handle();
示例#23
0
文件: index.php 项目: asha1412/dasshy
<?php

error_reporting(E_ALL);
use Phalcon\Mvc\Micro as App;
define('APP_PATH', realpath('../app'));
require APP_PATH . '/config/loader.php';
require APP_PATH . '/config/services.php';
//try {
$app = new App();
$app->setDI($di);
require APP_PATH . '/handlers.php';
$response = $app->handle();
if ($response instanceof Phalcon\Http\ResponseInterface) {
    $response->send();
}
//} catch (Exception $e) {
//	echo $app->view->render('errors/500', array(
//		'exception' => $e
//	));
//}
示例#24
0
<?php

use Phalcon\Mvc\Micro;
try {
    //Initialize Dependency Injection
    $di = new Phalcon\DI\FactoryDefault();
    //Initialize DB
    include_once __DIR__ . '/app/config/database.php';
    //Register Directories
    $loader = new \Phalcon\Loader();
    $loader->registerDirs(array(__DIR__ . '/app/models/', __DIR__ . '/app/controllers/', __DIR__ . '/app/classes/'))->register();
    // Use composer autoloader to load vendor classes
    require_once __DIR__ . '/vendor/autoload.php';
    //Create the app
    $app = new Micro();
    // Mount the routes
    $routes = (include_once __DIR__ . '/app/config/routes.php');
    foreach ($routes as $route) {
        $app->mount($route);
    }
    // Default Response
    $app->get('/', function () {
        return Rs::p(1, 'API is up!');
    });
    //Add any filter before running the route
    $app->before(function () use($app) {
        //You may want to add some basic auth in order to access the REST API
    });
    //This is executed after running the route
    $app->after(function () use($app) {
    });
示例#25
0
use Phalcon\DI\FactoryDefault;
use Phalcon\Db\Adapter\Pdo\Mysql as PdoMysql;
require __DIR__ . '/common/common.lib.php';
try {
    // 加载模块
    $loader = new Loader();
    $loader->registerDirs(array(__DIR__ . '/models/', __DIR__ . '/controller/'))->register();
    /**
     * @link https://docs.phalconphp.com/en/latest/reference/di.html
     */
    $di = new FactoryDefault();
    // 设置db
    $di->set('db', function () {
        return new PdoMysql(array("host" => "localhost", "username" => "root", "password" => "", "dbname" => "new-encounter"));
    });
    $app = new Micro($di);
    $app->get('/', function () {
        echo "Singou Encounter Back End API Server";
    });
    $app->get('/token', function () {
        return router('User', 'login', func_get_args());
    });
    $app->delete('/token', function () {
        return router('User', 'logout', func_get_args());
    });
    $app->get('/lottery', function () {
        return router('');
    });
    $app->post('/lottery', function () {
        return router('');
    });
示例#26
0
 /**
  * Read the configuration
  */
 include __DIR__ . '/../app/config/config.php';
 /**
  * Read auto-loader
  */
 include $config->app->baseDir . 'config/loader.php';
 /**
  * Read services
  */
 include $config->app->baseDir . 'config/services.php';
 /**
  * Create the application
  */
 $app = new Micro($di);
 /*
  * Configure HTTP response
  */
 $app->response->setHeader('Access-Control-Allow-Origin', '*');
 $app->response->setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Range, Content-Disposition, Content-Type, Authorization');
 /*
  * Add collections for routing
  */
 $collections = glob($config->app->collectionsDir . '*.php');
 foreach ($collections as $collection) {
     $app->mount(include_once $collection);
 }
 /**
  * Handle the request
  */
 /**
  * Add specified headers to a response.
  **/
 protected function addResponseHeaders(Micro $app, Response $response)
 {
     $appConfig = $app->getDI()->get(Application::DI_CONFIG);
     if (isset($appConfig['cors'])) {
         $response->setHeader('Access-Control-Allow-Origin', $appConfig['cors']);
     }
     //Attach headers always to request.
     foreach (static::$headers as $headerKey => $headerValue) {
         $response->setHeader($headerKey, $headerValue);
     }
     return $this;
 }
示例#28
0
$config = new ConfigIni(APP_PATH . 'app/config/config.ini');
$di->set('config', function () use($config) {
    return $config;
});
$di->set('mongo', function () use($config) {
    if (!$config->database_mongo->username || !$config->database_mongo->password) {
        $mongo = new MongoClient('mongodb://' . $config->database_mongo->host);
    } else {
        $mongo = new MongoClient("mongodb://" . $config->database_mongo->username . ":" . $config->database_mongo->password . "@" . $config->database_mongo->host, array("db" => $config->database->mongo->dbname));
    }
    return $mongo->selectDB($config->database_mongo->dbname);
}, TRUE);
$di->set('collectionManager', function () {
    return new Phalcon\Mvc\Collection\Manager();
}, true);
$app = new Micro();
$app->setDI($di);
$app->get('/test', function () use($app) {
    //        echo $app->config->application->controllersDir;
    //        echo $app->config->database->dbname;
    echo $app->mongo->selectCollection('restaurants')->count();
});
//下载对应csv文件
$app->get('/file/{pid:[0-9]+}', function ($pid) use($app) {
    $response = $app->response;
    $pid = '000000000' . $pid;
    $frontCache = new FrontData(array("lifetime" => 3600 * 240));
    $cache = new BackFile($frontCache, array("cacheDir" => "../app/storage/cache/"));
    $cacheKey = $pid;
    if ($cache->exists($cacheKey)) {
        $arr = json_decode($cache->get($cacheKey), true);
示例#29
0
use Phalcon\DI\FactoryDefault;
use Phalcon\Mvc\Micro;
define('APP_PATH', dirname(dirname(__FILE__)) . '/apps');
/**
 * Read the configuration
 */
$config = (require APP_PATH . '/config/config.php');
if ($config['debug']) {
    $debug = new \Phalcon\Debug();
    $debug->listen();
}
/**
 * The FactoryDefault Dependency Injector automatically register the right services providing a full stack framework
 */
$di = new FactoryDefault();
$app = new Micro($di);
// 日志
$di->setShared('logger', function () {
    return new \Phalcon\Logger\Adapter\File(APP_PATH . '/logs/' . date('Ymd') . '.log');
});
// api 规则路由
$apiRegister = (require_once APP_PATH . '/config/register.php');
// 注册命名空间
$loader = new \Phalcon\Loader();
$loader->registerNamespaces($apiRegister['namespace'])->register();
foreach ($apiRegister['list'] as $class => $conf) {
    $index = new Micro\Collection();
    $index->setHandler(new $class());
    $index->setPrefix($conf['prefix']);
    foreach ($conf['router'] as $router) {
        $index->{$router}[0]($router[1], $router[2]);
示例#30
0
<?php

use Phalcon\Mvc\Micro;
use Phalcon\Http\Response;
$app = new Micro();
$app->get('/api/frameworks', function () {
    $response = new Response();
    $response->setContentType('application/json');
    $data = [['name' => 'Zend', 'version' => '2.4.8'], ['name' => 'Symfony', 'version' => '2.7.5'], ['name' => 'Silex', 'version' => '1.3.4'], ['name' => 'Phalcon', 'version' => '2.0.8']];
    $response->setJsonContent($data);
    return $response;
});
$app->notFound(function () use($app) {
    $app->response->setStatusCode(404, 'Not Found')->sendHeaders();
    echo 'The requested resource is not found';
});
$app->handle();