Why is "Twig\Loader\FilesystemLoader" not found? - twig

I'm getting the following error and don't know why. I'm already including the autoload.php
Fatal error: Uncaught Error: Class "Twig\Loader\FilesystemLoader" not found in /Applications/MAMP/htdocs/php-blog/index.php:10 Stack trace: #0 {main} thrown in /Applications/MAMP/htdocs/php-blog/index.php on line 10
<?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;
use Twig\Environment;
use Twig\Loader\FilesystemLoader;
require __DIR__ . '/vendor/autoload.php';
$loader = new \Twig\Loader\FilesystemLoader('templates');
$view = new \Twig\Loader\Environment($loader);
$app = AppFactory::create();
$app->get('/', function (Request $request, Response $response, $args) use ($view) {
$body = $view->render('index.twig');
$response->getBody()->write("Hello world!");
return $response;
});
$app->get('/about', function (Request $request, Response $response, $args) {
$response->getBody()->write("About blog");
return $response;
});
$app->run();

Related

Too few arguments to function App\Controllers\Parsys::__construct(), 0 passed in

First I code without use RequestInterface and runwell, but I when I applicate the RequestInterface from the docs here: https://codeigniter4.github.io/userguide/incoming/incomingrequest.html I got this error, What happen with my code?
<?php namespace App\Controllers;
use CodeIgniter\HTTP\RequestInterface;
class Parsys extends BaseController {
protected $request;
public function __construct(RequestInterface $request) {
$this->request = $request;
}
public function index() {
$data = [
'title' => "Parameter System",
];
return view("backend/parsys_frm", $data);
}
public function getList() {
$frm = $request->getGet('frm');
$q = $this->request->getGet('q');
$order_by = $this->request->getGet('order_by');
$page = $this->request->getGet('page');
$limit = $this->request->getGet('limit');
$limit = #$limit == 0 ? 10 : $limit;
$this->queryList($total, $current, $page, $limit, $q, [1 => 1]);
$data = $current->result_array();
header('Content-Type: application/json');
echo json_encode(compact(['total', 'page', 'limit', 'data', 'q']));
}
I use ubuntu 20.04, lampp PHP 7.4
Instead of using the __construct magic method use the built in init method.
public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
}

Always the same view content on slim framework with twig after save changes

I'm using Slim and Twig and I'm trying to change a view content, but it doesn't change after I saved the changes.
This is the controller:
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
require '../../vendor/autoload.php';
require './classes/connection.php';
$app = new \Slim\App;
$container = $app->getContainer();
$container['view'] = function ($container) {
$view = new \Slim\Views\Twig('../../views', [
'cache' => '../../views_cache'
]);
// Instantiate and add Slim specific extension
$router = $container->get('router');
$uri = \Slim\Http\Uri::createFromEnvironment(new \Slim\Http\Environment($_SERVER));
$view->addExtension(new \Slim\Views\TwigExtension($router, $uri));
return $view;
};
$app->get('/hello/{name}', function (Request $request, Response $response, array $args) {
/*$name = $args['name'];
$response->getBody()->write("Hello, $name");
echo getcwd();
return $response;*/
return $this->view->render($response, 'login.html', [
'name' => $args['name']
]);
});
$app->post('/login', function (Request $request, Response $response, array $args) {
$post_data = $request->getParsedBody();
if (isset($post_data['user']) && isset($post_data['pass'])) {
$mongo = new Connection();
$conn = $mongo->getConnection();
$collection = $conn->prueba->users;
$result = $collection->find(['user' => $post_data['user']])->toArray();
$dbUser = $result[0]['username'];
$dbPass = $result[0]['password'];
if (password_verify($post_data['pass'], $dbPass)) {
echo '¡La contraseña es válida!';
} else {
echo 'La contraseña no es válida.';
}
} else {
return $response->withJson(array('login_status' => 'ko'));
}
});
$app->run();
What I missed to see the view changes? I think it's something about compile view but I'm not sure. It's the first time I use this framework.

Zend\Stdlib\Exception\BadMethodCallException

Here the part of the stacktrace where I have a problem:
Zend\Stdlib\Exception\BadMethodCallException
File:
/var/www/html/zf2/vendor/zendframework/zendframework/library/Zend/Stdlib/Hydrator/ArraySerializable.php:28
Message:
Zend\Stdlib\Hydrator\ArraySerializable::extract expects the provided object to implement getArrayCopy()
Stack trace:
0 /var/www/html/zf2/vendor/zendframework/zendframework/library/Zend/Form/Fieldset.php(631): Zend\Stdlib\Hydrator\ArraySerializable->extract(Object(BookList\Model\Book))
1 /var/www/html/zf2/vendor/zendframework/zendframework/library/Zend/Form/Form.php(942): Zend\Form\Fieldset->extract()
2 /var/www/html/zf2/vendor/zendframework/zendframework/library/Zend/Form/Form.php(303): Zend\Form\Form->extract()
3 /var/www/html/zf2/module/BookList/src/BookList/Controller/BookController.php(59): Zend\Form\Form->bind(Object(BookList\Model\Book))
The action method in my Controller that call bind:
public function editAction()
{
$id = (int) $this->params()->fromRoute('id', 0);
if (!$id) {
return $this->redirect()->toRoute('book');
}
try {
$book = $this->getBookTable()->getBook($id);
}
catch (\Exception $ex) {
return $this->redirect()->toRoute('book', array(
'action' => 'index'
));
}
$form = new BookForm();
$form->bind($book); // this is the line 59 of BookController
$form->get('submit')->setAttribute('value', 'Edit');
$request = $this->getRequest();
if ($request->isPost()) {
$form->setInputFilter($book->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$this->getBookTable()->saveBook($book);
// Redirect to list of books
return $this->redirect()->toRoute('book');
}
}
return array(
'id' => $id,
'form' => $form,
);
}
I checked also the BookTable class to see the object returned from the resulset and it's an istance of Book.
Than I opened the ArratSerializable.php and check the object passed and tre response is:
BookList\Model\Book Object ( [id] => 5 [author] => Gotye [title] => Making Mirrors [inputFilter:protected] => )
So it's a correct object, why doesn't it work?
How the result is returned you generally tell that to the ResultSet object while building your model. You actually set a prototype there for returning your result set saying, hey! "Use this prototype" which is, in your case, Book model. It does have a method called getArrayCopy() which is missing. That actually rises error in this case. So please add this to the Book model thus
class Book
{
// other properties and methods should be here
// add this method here
public function getArrayCopy()
{
return get_object_vars($this);
}
}

How can I pass object properties to onSyndicationSuccess event while using SMF.Net.WebClient dynamically

I'm trying to create a central function for dynamic web requests.
function makeWebRequest(remoteURL, requestString, callBackFunction) {
var myWebRequest = new SMF.Net.WebClient({
url : remoteURL,
httpMethod : "POST",
requestString : requestString,
requestHeaders : [
"Content-Type: application/x-www-form-urlencoded"],
onSyndicationSuccess : callBackFunction,
onServerError : function (e) {
alert(e);
}
});
myWebRequest.run(false);
}
While calling makeWebRequest, passing a callBackFunction to it like;
var remoteURL = "http://parse.com/12/test";
var requestString = "category=news&type=world";
function callBackFunction(e) {
responseText = this.responseText;
if (responseText != null) {
parsedJSON = JSON.parse(responseText);
}
}
makeWebRequest(remoteURL,requestString,callBackFunction);
Application raises an error at line
responseText = this.responseText;
How can I pass myWebRequest itself to a function like that?
I used your codeLines. I just add a textButton to Page1, and it works fine both for Android and iOS .
In Global.js;
function makeWebRequest(remoteURL, requestString, callBackFunction) {
var myWebRequest = new SMF.Net.WebClient({
url : remoteURL,
httpMethod : "POST",
requestString : requestString,
requestHeaders : [
"Content-Type: application/x-www-form-urlencoded"],
onSyndicationSuccess : callBackFunction,
onServerError : function (e) {
alert(e);
}
});
myWebRequest.run(false);
}
var remoteURL = "http://parse.com/12/test";
var requestString = "category=news&type=world";
function callBackFunction(e) {
var responseText = this.responseText;
alert(responseText);
if (responseText != null) {
parsedJSON = JSON.parse(responseText);
}
}
function Global_Events_OnStart(e) {
changeLang(Device.language, true);
include("BC.js"); //included for future BC support. Removing is not advised.
// Comment following block for navigationbar/actionbar sample. Read the JS code file for usage.
// Also there is a part of code block in Page1, which should be copied to every page for HeaderBar usage
load("HeaderBar.js");
header = new HeaderBar();
// Uncomment following block for menu sample. Read the JS code file for usage.
/*
load("Menu.js");
/**/
}
function Global_Events_OnError(e) {
switch (e.type) {
case "Server Error":
case "Size Overflow":
alert(lang.networkError);
break;
default:
SES.Analytics.eventLog("error", JSON.stringify(e));
//change the following code for desired generic error messsage
alert({
title : lang.applicationError,
message : e.message + "\n\n*" + e.sourceURL + "\n*" + e.line + "\n*" + e.stack
});
break;
}
}
In Page1.js;
function Page1_Self_OnKeyPress(e) {
if (e.keyCode === 4) {
Application.exit();
}
}
function Page1_Self_OnShow() {
//Comment following block for removing navigationbar/actionbar sample
//Copy this code block to every page onShow
header.init(this);
header.setTitle("Page1");
header.setRightItem("RItem");
header.setLeftItem();
/**/
}
function Page1_TextButton1_OnPressed(e){
makeWebRequest(remoteURL,requestString,callBackFunction);
}
it works fine. Check your makeWebRequest function, must be on Global.js. Also define "responseText" variable with "var".

Wrong usage of MVC #helper?

I made a helper which is meant to help me debug my app.
It firsts display a header.
Then it tries to run a block of code which returns a fews arguments (array of objects).
Those arguments are used in a string format which is displayed when the block ran fine.
If the block caused an exception, the exception gets displayed.
The problem is, nothing gets displayed at all when I call the helper (I'm very new to that feature).
What's wrong?
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
#using MygLogWeb.Classes.Fox
<span>test</span>
#helper TryMethod(
string header
, Func<object[]> act
, string successFormat
)
{
#Html.Raw(String.Format(
#"<h2>{0}</h2>"
, HttpUtility.HtmlEncode(header)
));
try
{
var args = act();
if (successFormat == null)
{
#Html.Raw(#"<span class='Success'>OK</span>");
}
else
{
#Html.Raw(String.Format(
#"<span class='Success'>{0}</span>"
, HttpUtility.HtmlEncode(String.Format(
successFormat
, args
))
));
}
}
catch (Exception exe)
{
#Html.Raw(String.Format(
#"<span class='Error'>{0}</span>"
, HttpUtility.HtmlEncode(exe.Message)
));
}
}
<span>test</span>
#{
TryMethod(
"Cust.Columns"
, () => {
return new object[]
{
Cust.Columns.Count
};
}
, "Count: {0}"
);
}
<span>test</span>
The problem is not with the helper method itself but with the execution.
When you execute like this:
#{
TryMethod(...);
}
the code is executed but it's a code block but not written to output.
Use this syntax instead:
#(TryMethod(...))
this should work.

Resources