Exemplo n.º 1
0
 /**
  * Tests the notFound
  *
  * @issue T169
  * @author Nikos Dimopoulos <*****@*****.**>
  * @since 2012-11-06
  */
 public function testMicroNotFoundT169()
 {
     $this->specify("MVC Micro notFound doesn't work", function () {
         $handler = new \RestHandler();
         $app = new Micro();
         $app->get("/api/site", [$handler, "find"]);
         $app->post("/api/site/save", [$handler, "save"]);
         $flag = false;
         $app->notFound(function () use(&$flag) {
             $flag = true;
         });
         $_SERVER["REQUEST_METHOD"] = "GET";
         $_GET["_url"] = "/fourohfour";
         $app->handle();
         expect($flag)->true();
     });
 }
Exemplo n.º 2
0
    $c->sku = (string) $obj->codigo;
    $c->nome = (string) $obj->nome;
    $c->parent_sku = (string) $obj->parent;
    $erros = array();
    if (!$c->save()) {
        $erros['codigo_produto'] = $obj->codigo;
        foreach ($user->getMessages() as $message) {
            $erros['mensagem'][] = $message->getMessage();
        }
        return $erros;
    } else {
        return true;
    }
}
$app->get('/', function () {
    echo "<h1>Api Sualoja.online!</h1>";
});
##################################################
####### PRODUTOS
###################################################
// Retorna todos os produtos cadastrados na loja
$app->get('/products/{key}', function ($key) use($app, $di) {
    $response = new Response();
    $response->setHeader('Content-Type', 'application/xml');
    $conta = Contas::findFirst(array('conditions' => array('key' => $key)));
    if ($conta) {
        setDatabase($di, $conta->host, $conta->database);
        $dados = Produtos::find();
        $xml = new SimpleXMLElement("<?xml version='1.0' encoding='ISO-8859-1'?><response/>");
        $xml->addChild('status', 'OK');
        $produtos = $xml->addChild('produtos');
Exemplo n.º 3
0
    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();
});
/**
 * Get specific image
 */
$app->get('/image/{id:[0-9]+}', function ($id) use($app, $response) {
    $image = new Images();
    $response->setJsonContent($image->getImageInfo($id));
    $response->send();
});
/**
 * Get latest tags
 */
$app->get('/tags/latest', function () use($app, $response) {
Exemplo n.º 4
0
$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);
        if (isset($arr['file_path']) && !empty($arr['file_path'])) {
            $content = file_get_contents($arr['file_path']);
            $response->setContentType('application/csv');
            $response->setContent($content);
Exemplo n.º 5
0
<?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();
Exemplo n.º 6
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();
Exemplo n.º 7
0
<?php

use Phalcon\Mvc\Micro, Phalcon\Db\Adapter\Pdo\Mysql as MysqlAdapter;
$app = new Micro();
//Setup the database service
$app['db'] = function () {
    return new MysqlAdapter(array("host" => "localhost", "username" => "root", "password" => "secret", "dbname" => "test_db"));
};
$app->get('/blog', function () use($app) {
    $news = $app['db']->query('SELECT * FROM news');
    foreach ($news as $new) {
        echo $new->title;
    }
});
Exemplo n.º 8
0
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('');
    });
    $app->notFound(function () {
        return router('Base', 'error', array('0001', 404));
///
// Set up the database service
$di->set('db', function () {
    return new \Phalcon\Db\Adapter\Pdo\Mysql(array("host" => DATABASE_HOST, "username" => DATABASE_USER, "password" => DATABASE_PASSWORD, "dbname" => DATABASE_NAME));
});
$app = new Micro($di);
//COR'S STUFF
$app->before(function () use($app) {
    $origin = $app->request->getHeader("ORIGIN") ? $app->request->getHeader("ORIGIN") : '*';
    $app->response->setHeader("Access-Control-Allow-Origin", $origin)->setHeader("Access-Control-Allow-Methods", 'GET,PUT,POST,DELETE,OPTIONS')->setHeader("Access-Control-Allow-Headers", 'Origin, X-Requested-With, Content-Range, Content-Disposition, Content-Type, Authorization')->setHeader("Access-Control-Allow-Credentials", true)->setHeader("'Content-type", 'application/json');
});
$app->options('/{catch:(.*)}', function () use($app) {
    $app->response->setStatusCode(200, "OK")->send();
});
$app->get('/', function () use($app, $response) {
    $data = array('rubix trader racing mock api');
    $response->send(200, 'ok', $data);
});
//get all venue information
$app->get('/venues', function () use($app, $response) {
    $sql = "SELECT v.*, s.*, f.*, va.*\n\t\t\tFROM venue AS v\n\t\t\tINNER JOIN sport AS s ON s.sport_id = v.sport_id\n\t\t\tLEFT JOIN venueAlias AS va ON va.venue_id = v.venue_id\n\t\t\tLEFT JOIN feed AS f ON f.feed_id = va.feed_id\n\t\t\t";
    $results = $app->modelsManager->executeQuery($sql);
    $code = 200;
    $responseText = 'ok';
    $data = array();
    foreach ($results as $row) {
        $data[] = array('venue_id' => $row->v->venue_id, 'venue_name' => $row->v->name, 'sport_id' => $row->s->sport_id, 'sport_name' => $row->s->name, 'venue_alias_id' => $row->va->venue_alias_id, 'feed_id' => $row->f->feed_id, 'feed_name' => $row->f->name);
    }
    $response->send($code, $responseText, $data);
});
//get meetings for a sport
$app->get('/categories/{category_name:[a-z]*}', function ($category_name) use($app, $response) {
Exemplo n.º 10
0
// 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" => "localhost", "username" => "autos", "password" => "autos", "dbname" => "autos"));
});
// Create and bind the DI to the application
$app = new Micro($di);
//Show all Cars
$app->get('/api/autos', function () use($app) {
    $phql = "SELECT * FROM Cars ORDER BY id";
    $cars = $app->modelsManager->executeQuery($phql);
    $data = array();
    foreach ($cars as $car) {
        $data[] = array('id' => $car->id, 'Make' => $car->Make, 'Model' => $car->Model, 'Colour' => $car->Colour, 'Engine' => $car->Engine, 'Year' => $car->Year);
    }
    echo json_encode($data);
});
// Searches for Cars by Make
$app->get('/api/autos/search/{make}', function ($make) use($app) {
    $phql = "SELECT * FROM Cars WHERE Make LIKE :make: ORDER BY id";
    $cars = $app->modelsManager->executeQuery($phql, array('make' => '%' . $make . '%'));
    $data = array();
    foreach ($cars as $car) {
        $data[] = array('id' => $car->id, 'Make' => $car->Make, 'Model' => $car->Model, 'Colour' => $car->Colour, 'Engine' => $car->Engine, 'Year' => $car->Year);
    }
    echo json_encode($data);
});
// Retrieves Car based on primary key
Exemplo n.º 11
0
<?php

use Phalcon\Mvc\Micro;
$app = new Micro();
$app->view = function () {
    $view = new \Phalcon\Mvc\View();
    $view->setViewsDir('views/');
    return $view;
};
$app->get('/', function () {
    echo "<h1>Welcome!</h1>";
});
$app->handle();
Exemplo n.º 12
0
<?php

use Phalcon\DI\FactoryDefault, Phalcon\Mvc\Micro, Phalcon\Config\Adapter\Ini as IniConfig;
$di = new FactoryDefault();
$di->set('config', function () {
    return new IniConfig("config.ini");
});
$app = new Micro();
$app->setDI($di);
$app->get('/', function () use($app) {
    //Read a setting from the config
    echo $app->config->app_name;
});
$app->post('/contact', function () use($app) {
    $app->flash->success('Yes!, the contact was made!');
});
Exemplo n.º 13
0
<?php

use Phalcon\Mvc\Micro;
use Phalcon\Di\FactoryDefault;
use Phalcon\Http\Response;
$di = new FactoryDefault();
$di->set('response', function () {
    return new Response();
});
$app = new Micro($di);
// Index
$app->get('/', function () use($app) {
    return ['service' => 'Payment', 'version' => '0.0.0'];
});
// Return JSON
$app->after(function () use($app) {
    return $app->response->setContentType('application/json', 'UTF-8')->setJsonContent($app->getReturnedValue())->send();
});
$app->handle();
Exemplo n.º 14
0
<?php

use Phalcon\Mvc\Micro, Phalcon\Http\Response;
$app = new Micro();
//Return a response
$app->get('/welcome/index', function () {
    $response = new Response();
    $response->setStatusCode(401, "Unauthorized");
    $response->setContent("Access is not authorized");
    return $response;
});
Exemplo n.º 15
0
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}
function _test($data)
{
    echo "<pre>";
    print_r($data);
    echo "</pre>";
}
//Create and bind the DI to the application
$app = new Micro($di);
$app->get('/', function () use($app) {
    echo 'Welcome to kajian API';
});
foreach (glob("routes/*.php") as $filename) {
    include $filename;
}
$app->notFound(function () use($app) {
    $app->response->setStatusCode(404, "Not Found")->sendHeaders();
    echo 'This is crazy, but this page was not found!';
});
$app->before(function () use($app) {
    $origin = $app->request->getHeader("ORIGIN") ? $app->request->getHeader("ORIGIN") : '*';
    $content_type = 'application/json';
    $status = 200;
    $description = 'OK';
    $response = $app->response;
    $status_header = 'HTTP/1.1 ' . $status . ' ' . $description;
Exemplo n.º 16
0
require __DIR__ . '/../vendor/autoload.php';
// 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" => "stumpdk", "password" => "", "dbname" => "test"));
});
$app = new Micro($di);
$response = new Response();
// Define the routes here
// Retrieves all robots
$app->get('/image/random', function () use($app) {
    $robots = Images::find();
    echo "There are ", count($robots), "\n";
    // $result = Images::query('select min(id), max(id) FROM images;');
});
$app->get('/image/{id:[0-9]+}', function ($id) use($app, $response) {
    // $images = Images::findFirstById($id);
    // $response->setJsonContent($images->imagesTags);
    //$response->setJsonContent($images);
    //$image = Images::findFirstById($id);
    //$response->setJsonContent($image->imagesTags);
    $images = Images::findById($id);
    //(['limit' => 10]);
    $data = [];
    $i = 0;
    foreach ($images as $image) {
        foreach ($image->getImagesTags() as $tag) {
            foreach ($tag->getTags() as $tag2) {
Exemplo n.º 17
0
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();
$loader->registerDirs(array(__DIR__ . '/models/'))->register();
$di = new FactoryDefault();
// Set up the database service
$di->set('db', function () {
    return new PdoMysql(array("host" => "justinlegoff.com", "username" => "root", "password" => "ecudeSobieski14", "dbname" => "gamification_db"));
});
// Create and bind the DI to the application
$app = new Micro($di);
// Retrieves all users
$app->get('/api/users', function () {
    $phql = "SELECT * FROM Member";
    $users = $app->modelsManager->executeQuery($phql);
    $data = array();
    foreach ($users as $user) {
        $data[] = array('mbr_id' => $user->mbr_id, 'mbr_firstname' => $user->mbr_firstname, 'mbr_lastname' => $user->mbr_lastname);
    }
    echo json_encode($data);
});
// Searches for user with $name in their name
$app->get('/api/user/{name}', function ($name) {
});
// Retrieves user based on primary key
$app->get('/api/user/{id:[0-9]+}', function ($id) {
});
$app->handle();
Exemplo n.º 18
0
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));
    $data = array();
Exemplo n.º 19
0
                return false;
            } else {
                // success, do nothing
            }
        } else {
            // if cookies are set, they would have already been handled by auth.php
        }
        // Return false to stop the operation
        return true;
    }
});
$app = new Micro();
// Bind the events manager to the app
$app->setEventsManager($eventManager);
$app->get('/', function () use($app) {
    echo file_get_contents('index.html');
});
/**
 * GET /api/threads?id=-1&count=50
 *
 * Returns "Collapsed threads" view data, also a default view for mobile client. optional arguments - $max_thread_id, $count
 */
$app->get('/api/threads', function () use($app) {
    $id = $app->request->getQuery('id');
    if (is_null($id)) {
        $id = -1;
    } else {
        $id = intval($id);
    }
    $count = $app->request->getQuery('count');
    $response = new Response();
Exemplo n.º 20
0
<?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();
Exemplo n.º 21
0
<?php

use Phalcon\Mvc\Micro;
$app = new Micro();
// Retrieves all robots
$app->get('/api/robots', function () {
    //echo 111;
});
// Searches for robots with $name in their name
$app->get('/api/robots/search/{name}', function ($name) {
});
// Retrieves robots based on primary key
$app->get('/api/robots/{id:[0-9]+}', function ($id) {
});
// Adds a new robot
$app->post('/api/robots', function () {
});
// Updates robots based on primary key
$app->put('/api/robots/{id:[0-9]+}', function () {
});
// Deletes robots based on primary key
$app->delete('/api/robots/{id:[0-9]+}', function () {
});
//$app->handle()->getContent();
Exemplo n.º 22
0
    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) {
    });
    // Not Found
    $app->notFound(function () use($app) {
        return Rs::p(0, 'Not Found', [], 404);
    });
    $app->handle();
} catch (\Exception $e) {
    return Rs::p(0, 'There was an error processing your request', $e->getMessage(), 400);
Exemplo n.º 23
0
        return new Database(array("host" => $config->database->host, "username" => $config->database->username, "password" => $config->database->password, "dbname" => $config->database->name));
    });
    /**
     * Registering an autoloader
     */
    $loader = new Loader();
    $loader->registerDirs(array($config->application->modelsDir))->register();
    /**
     * Starting the application
     */
    $app = new Micro();
    /**
     * Add your routes here
     */
    $app->get('/', function () {
        require __DIR__ . "/../views/index.phtml";
    });
    /**
     * Not found handler
     */
    $app->notFound(function () use($app) {
        $app->response->setStatusCode(404, "Not Found")->sendHeaders();
        require __DIR__ . "/../views/404.phtml";
    });
    /**
     * Handle the request
     */
    $app->handle();
} catch (\Exception $e) {
    echo $e->getMessage(), PHP_EOL;
    echo $e->getTraceAsString();
Exemplo n.º 24
0
//----------------------------
$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) {
    $phql = "SELECT * FROM Products WHERE id = :id:";
    //Products is table name
    $product = $app->modelsManager->executeQuery($phql, array('id' => $id))->getFirst();
    // create a response
    $response = new Response();
    if ($product == false) {
        $response->setJsonContent(array('status' => 'NOT-FOUND'));
    } else {
        $response->setJsonContent(array('status' => 'FOUND', 'data' => array('id' => $product->id, 'name' => $product->name, 'price' => $product->price, 'in_stock' => $product->in_stock)));
Exemplo n.º 25
0
use Phalcon\Loader;
use Phalcon\Mvc\Micro;
use Phalcon\Di\FactoryDefault;
use Phalcon\Db\Adapter\Pdo\Mysql as PdoMysql;
use Phalcon\Paginator\Adapter\QueryBuilder;
header('Content-type: application/json; charset=utf-8');
ini_set('display_errors', 1);
error_reporting(E_ALL);
$loader = new Loader();
$loader->registerDirs([__DIR__ . '/../phalcon/models/'])->register();
$di = new FactoryDefault();
$di->set('db', function () {
    return new PdoMysql(require __DIR__ . '/../phalcon/config.php');
});
$app = new Micro($di);
$app->get('/v1/get/{hash}/{page:[0-9]+}', 'myGet');
$app->get('/v1/get/{hash}', 'myGet');
$app->notFound(function () use($app) {
    $app->response->setStatusCode(404, "Not Found")->sendHeaders();
    echo 'Not found';
});
$app->handle();
function myGet($hash, $page = 0)
{
    global $app;
    $CG = new ContentGeneration();
    if ($CG->getHash($hash)) {
        if ($page !== '0') {
            $CG->getLink($page);
        }
        echo $CG->response();
Exemplo n.º 26
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();
Exemplo n.º 27
0
    $mongo = new MongoClient();
    return $mongo->selectDB('tab');
}, true);
$di->set('collectionManager', function () {
    return new CollectionManager();
}, true);
$app = new Micro($di);
//======================================================================
// MICRO ROUTER
//======================================================================
// Show all sources from db
$app->get('/sources', function () use($app) {
    $sources = Tabs\Models\Sources::find();
    if ($sources) {
        $app->response->setContent(json_encode(array('sources' => $sources)))->send();
    } else {
        $app->response->setStatusCode(404, 'Not Found');
        $app->response->setJsonContent(array('status' => 'Not Found'))->send();
    }
});
// Show one source from db selected by id
$app->get('/sources/{id}', function ($id) use($app) {
    $source = Tabs\Models\Sources::findById((string) $id);
    if ($source) {
        $app->response->setContent(json_encode(array('source' => $source)))->send();
    } else {
        $app->response->setStatusCode(404, 'Not Found');
        $app->response->setJsonContent(array('status' => 'Not Found'))->send();
    }
});
// Show prepared data from sources selected by id
Exemplo n.º 28
0
$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 . '%'));
    $data = array();
    foreach ($robots as $robot) {
        $data[] = array('id' => $robot->id, 'name' => $robot->name);
    }
    echo json_encode($data);
});
// Retrieves robots based on primary key
            }
        } catch (Exception $e) {
            $response->setStatusCode(503, "Internal Server Error");
            $response->setJsonContent(array("message" => $e->getMessage()));
        }
    } else {
        $response->setStatusCode(400, "Bad Request");
        $response->setJsonContent(array("message" => $respond));
    }
    return $response;
});
$app->get("/status/db/{id}", function ($id) {
    # Start building the response.
    $response = new Response();
    # Fill the response with the return value of the function that checks
    # the status of the component.
    $response->setStatusCode(200, "OK");
    $response->setJsonContent(array("ready" => check_db($id)));
    return $response;
});
$app->get("/status/memcached/{id}", function ($id) {
    # Start building the response.
    $response = new Response();
    # Fill the response with the return value of the function that checks
    # the status of the component.
    $response->setStatusCode(200, "OK");
    $response->setJsonContent(array("ready" => check_memcached($id)));
    return $response;
});
$app->get("/status/zebra/{id}", function ($id) {
    # Start building the response.