Twig Swiftmailer without Symfony - php

I'm trying to use Standalone Twig to send emails with Swiftmailer. I'm following for the instructions at the "With a pure Swiftmailer/Twig" section.
This is my code:
require_once('/var/www/folder/includes/vendor/autoload.php');
$loader = new Twig_Loader_Filesystem(array('/var/www/templates/utilities/test'));
$twig = new Twig_Environment($loader, array(
'cache' => '/var/www/templates/cached',
'auto_reload' => true, // set to false to improve performance (Note: You have to clear the cache manually whenever a template is changed)
'debug' => true,
'use_strict_variables' => false,
));
$twig->addExtension(new Twig_Extension_Debug());
$swiftMailerTemplateHelper = new \WMC\SwiftmailerTwigBundle\TwigSwiftHelper($twig, '/var/www/templates/utilities/test');
// I'm not exactly sure what the value for the second parameter is supposed to be.
//The instructions referenced just list a variable called $web_directory.
//I'm assuming they just mean a path to where the templates are stored.
echo "hello world";
This is the error I'm getting:
PHP Fatal error: Class
'WMC\SwiftmailerTwigBundle\TwigSwiftHelper' not found in
/var/www/apps_mymea/utilities/test/email.php on line 16

The namespace in the referenced documentation is incorrect.
The correct syntax is:
$swiftMailerTemplateHelper = new \WMC\SwiftmailerTwigBundle\Mailer\TwigSwiftHelper($twig, '/var/www/templates/utilities/test');
//It was missing the \Mailer\ in the class path.

Related

Uncaught Error: Class 'Discord\Client' not found PHP

I am working with Php and "Discord". Right now, I am getting the following error:
Fatal error: Uncaught Error: Class 'Discord\Client' not found",But in my "src folder
Client library exists, I have "Vendor" and "src" folders, and client.php is there. Here is my code - where I am going wrong?
<?php
include __DIR__.'/vendor/autoload.php';
include 'vendor/autoload.php';
use Discord\Discord;
use Discord\Parts\Interactions\Command\Command; // Please note to use this correct namespace!
use Discord\Client;
use Discord\Parts\Interaction;
use Discord\Parts\Choices;
$client = new Client([
'public_key' => 'b81678ce3e98ff78f9387c3cxxxxxxxxxxxxxxxx',
'uri' => '0.0.0.0:80', // if you want the client to listen on a different URI
'logger' => $logger, // different logger, default will write to stdout
'loop' => $loop, // reactphp event loop, default creates a new loop
'socket_options' => [], // options to pass to the react/socket instance, default empty array
]);
You need to use
$client = new Discord([
'token' => 'b81678ce3e98ff78f9387c3cxxxxxxxxxxxxxxxx'
]);
Instead of client because library team-reflex/discord-php using Discord class instead of Client in direct interaction.
Here you can find the use cases.

Drupal 8 custom module add php classes

I have created a custom Drupal 8 module that works as is with a custom block and block form to collect some info.
This is all good.
I also have a twig template that I want to render a twitter feed using a php feed class I bought. I just don't know how it integrate this into the module.
This is the setup for the class: http://austinbrunkhorst.com/demos/twitter-class/#setup
It contains two files:
ultimate.twitter.feed.php
and
tmhOAuth.php
Which is currently a require_once 'tmhOAuth.php'; in the head of ultimate.twitter.feed.php
According to the instruction I should be creating a php file that has this:
$options = array(
'screen_name' => 'FeedTestUser',
'consumer_key' => '...',
'consumer_secret' => '...',
'user_token' => '...',
'user_secret' => '...',
);
$twitter = new Twitter($options);
$twitter->PrintFeed();
Which I'm guessing is also a hurdle as twig files are not php
Any help with this is very much appreciated.
C
I would setup the class as a Service in your module. Your block will then implement that service and do the handling. You don't really want to use require_once() if you can avoid it, rather use Drupal constructs (in part so that if you reorganize things later Drupal will help find the files in their new location).
Place the class in your module's src directory, and add a namespace to the start of the file (assuming there isn't one there already). Then in your block's class file you should be able to add a use statement that references that name space (even better would be to use a dependency injection, but the details on that would get in your way here).
In your block class's build() method you then instantiate the class as described in your question, but instead of just letting the module print HTML, you can want to capture that HTML and place it into your block as markup. If the class allows you to do that without using a buffer, you should (but I didn't see anything in the docs to support that), and then attempt to theme the structured data. If not, you can use PHP's output buffering to capture its attempt to print:
ob_start();
$twitter->PrintFeed();
$content= ob_get_contents();
ob_end_clean();
Then place the generated markup into a render array:
return [
'my_twitter_block' => [
'#markup' => $content,
],
];
Create a custom block and add the result of PrintFeed() to the render array. Just as with any usual custom block. In the render array you can specify a template which should be used (if needed). If you wanna output pure html without any template you could use the '#markup' key.
Small example:
Your block render array:
return array(
'#theme' => 'name_of_your_theme',
'#some_twig_variable' => $twitter->PrintFeed();
);
your your_module.module file (in the root of your module folder):
function your_module_theme() {
return array(
'name_of_your_theme' => array(
'variables' => array(
'some_twig_variable' => some-default-value,
),
),
);
}
your name-of-your-theme.html.twig template (should be under your_module/templates):
{{ some_twig_variable }}
As far as using the class: I see no problem using a require_once for that matter (in your Block php file). Of course it's always better/nicer if you can require the library/package via the make file or composer and then use the autoloader, but if that's not possible just put it e.g. in your drupal root under /libraries/twitter or so and then require it. If you do it like that you have to check that library into your git repository obviously.
have you use ultimate.twitter.feed.php in your TwitterBlock.php file
If not then try adding this line before class block beginns:
require_once 'path/to/twitter_class/ultimate.twitter.feed.php';

ZF2 project stops working when is cloned to local server

I would like to know why when I clone my ZF2 project to a local machine to do some testing it completly stops working.
In my local machine I have two subfolders, one with a cakePHP project and the other with the ZF2 I've cloned.
The cakePHP project is working fine since it was there first, but the ZF2, when I try to access to the public folder it prints me:
{"error":"Something went wrong"}
A really generic error... I have no clue about what is going on.
I've tried some general debug attemps like
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
with no success at all, I've also checked the .htaccess RewriteBase directive to match my subfolder and the DB configuration is done too.
I have researched a bit in the project and the file which displays the error is module/RestfulV2_2/Module.php (Reading the README.md I've discovered is part of ZF2 Restful Module Skeleton):
/**
* #param MvcEvent $e
* #return null|\Zend\Http\PhpEnvironment\Response
*/
public function errorProcess(MvcEvent $e)
{
/** #var \Zend\Di\Di $di */
$di = $e->getApplication()->getServiceManager()->get('di');
$eventParams = $e->getParams();
/** #var array $configuration */
$configuration = $e->getApplication()->getConfig();
$vars = array();
if (isset($eventParams['exception'])) {
/** #var \Exception $exception */
$exception = $eventParams['exception'];
if ($configuration['errors']['show_exceptions']['message']) {
$vars['error-message'] = $exception->getMessage();
}
if ($configuration['errors']['show_exceptions']['trace']) {
$vars['error-trace'] = $exception->getTrace();
}
}
if (empty($vars)) {
$vars['error'] = 'Something went wrong';
}
/** #var PostProcessor\AbstractPostProcessor $postProcessor */
$postProcessor = $di->get(
$configuration['errors']['post_processor'],
array('vars' => $vars, 'response' => $e->getResponse())
);
$postProcessor->process();
if (
$eventParams['error'] === \Zend\Mvc\Application::ERROR_CONTROLLER_NOT_FOUND ||
$eventParams['error'] === \Zend\Mvc\Application::ERROR_ROUTER_NO_MATCH
) {
$e->getResponse()->setStatusCode(\Zend\Http\PhpEnvironment\Response::STATUS_CODE_501);
} else {
$e->getResponse()->setStatusCode(\Zend\Http\PhpEnvironment\Response::STATUS_CODE_500);
}
$e->stopPropagation();
return $postProcessor->getResponse();
}
The line which is calling the error in my index.php is:
Zend\Mvc\Application::init(require 'config/application.config.php')- run();
And the only line I found where the error function is called some way is this one in my modele.php :
$sharedEvents->attach('Zend\Mvc\Application', MvcEvent::EVENT_DISPATCH_ERROR, array($this, 'errorProcess'), 999);
Can you help me to solve this? I'm inexperienced with ZF2 but I know that with cakePHP to make it work you need to clear the cache folder. Is there any similar process in ZF2? Should I virtualize two servers to avoid conflics?
Thank you in advance.
EDIT : I've already made virtual hosts to avoid any possible conflict between my two frameworks but the error output is still the same.
EDIT2 : Here is my application.config.php file:
return array(
// This should be an array of module namespaces used in the application.
'modules' => array(
'Restful',
'MvlabsSnappy',
'Qrcode',
'Application',
'RestfulV2',
'RestfulV2_2'
),
// These are various options for the listeners attached to the ModuleManager
'module_listener_options' => array(
// This should be an array of paths in which modules reside.
// If a string key is provided, the listener will consider that a module
// namespace, the value of that key the specific path to that module's
// Module class.
'module_paths' => array(
'./module',
'./vendor',
),
// An array of paths from which to glob configuration files after
// modules are loaded. These effectively override configuration
// provided by modules themselves. Paths may use GLOB_BRACE notation.
'config_glob_paths' => array(
'config/autoload/{,*.}{global,local}.php',
),
// Whether or not to enable a configuration cache.
// If enabled, the merged configuration will be cached and used in
// subsequent requests.
//'config_cache_enabled' => $booleanValue,
// The key used to create the configuration cache file name.
//'config_cache_key' => $stringKey,
// Whether or not to enable a module class map cache.
// If enabled, creates a module class map cache which will be used
// by in future requests, to reduce the autoloading process.
//'module_map_cache_enabled' => $booleanValue,
// The key used to create the class map cache file name.
//'module_map_cache_key' => $stringKey,
// The path in which to cache merged configuration.
//'cache_dir' => $stringPath,
// Whether or not to enable modules dependency checking.
// Enabled by default, prevents usage of modules that depend on other modules
// that weren't loaded.
// 'check_dependencies' => true,
),
// Used to create an own service manager. May contain one or more child arrays.
//'service_listener_options' => array(
// array(
// 'service_manager' => $stringServiceManagerName,
// 'config_key' => $stringConfigKey,
// 'interface' => $stringOptionalInterface,
// 'method' => $stringRequiredMethodName,
// ),
// )
// Initial configuration with which to seed the ServiceManager.
// Should be compatible with Zend\ServiceManager\Config.
// 'service_manager' => array(),
);
First I would open index.php or whatever used as initial file (DirectoryIndex) and temporarily completely replace whole its content with something very base and simple, for example just these two lines:
<?php
phpinfo();
And then make sure that it started to work after that - with that simple code which just displays your php configuration. So we'll find out that there is no error in server configurations, permissions and etc. and nothing prevents your script from run.
Then I would do the same at your old project location just to get phpinfo() from that place too and waste some time trying to compare them. Maybe you missed something important and you'll now see it.
If no - next step I would check your DB connectivity if your project uses any DB... also with some very simple commands like connect, bind, ....
And finally I'd try to restore original project content step by step from its begin, and look at which step it will fail. It doesn't matter that there maybe no any output - you may put echo __LINE__ . ' works!<br/>'; between blocks, so your index.php will look like:
<?php
// original code block 1
echo __LINE__ . ' works!<br/>';
// original code block 2
echo __LINE__ . ' works!<br/>';
And you'll see in browser where it fails.
This is a very base description of my debug principals, but hope it will help.
The error could be anything. However, assuming the posted code is executed, it will suppress an error message without the correct configuration.
Try adding the following config to local.config.php.
return [
'errors'=> [
'show_exceptions' => [
'message' => true,
'trace' => true
],
],
];
If an exception is being thrown and that listener is catching it, then the $eventParams is something you should debug.

Using FirePHP with Zend Framework 2

I'm trying to use FirePHP with Zend Framework 2, but there seems to be something missing. Here's the basic code I'm trying to run:
$writer = new Zend\Log\Writer\FirePhp();
$logger = new Zend\Log\Logger();
$logger->addWriter($writer);
$logger->info('FirePHP logging enabled');
The error I get is "FirePHP Class not found". I was initially puzzled because I do have a FirePhp class in my Zend/Log/Writer folder. But then I saw that the class constructor requires a FirePhp\FirePhpInterface object. So I checked the Zend/Log/Writer/FirePhp folder and there's a FirePhpBridge class in there that implements FirePhpInterface, but it also requires a FirePHP instance in the constructor. I don't have any FirePHP.php file in my Zend/Log/Writer/FirePhp folder. Am I supposed to get this from somewhere else?
Update
I now have managed to get FirePHP working, but I'm trying to figure out how to do it in a clean way so this works. The only way I've gotten it to work is putting it in the root directory of my project and doing the following:
include_once('FirePHP.php');
$writer = new Zend\Log\Writer\FirePhp(new Zend\Log\Writer\FirePhp\FirePhpBridge(FirePHP::getInstance(true)));
$logger = new Zend\Log\Logger();
$logger->addWriter($writer);
$logger->info('FirePHP logging enabled');
I assume that normally I should be able to create a writer like so:
$writer = new Zend\Log\Writer\FirePhp();
However, where this goes wrong I believe is in the getFirePhp() function of the Zend\Log\Writer\FirePhp class. The class does this:
if (!$this->firephp instanceof FirePhp\FirePhpInterface
&& !class_exists('FirePHP')
) {
// No FirePHP instance, and no way to create one
throw new Exception\RuntimeException('FirePHP Class not found');
}
// Remember: class names in strings are absolute; thus the class_exists
// here references the canonical name for the FirePHP class
if (!$this->firephp instanceof FirePhp\FirePhpInterface
&& class_exists('FirePHP')
) {
// FirePHPService is an alias for FirePHP; otherwise the class
// names would clash in this file on this line.
$this->setFirePhp(new FirePhp\FirePhpBridge(new FirePHPService()));
}
This is where I get lost as to how I'm supposed to set things up so that this class_exists('FirePHP') call finds the right class and new FirePHPService() also works properly.
First you should add this code to Module.php of your module
return array(
//...
'Zend\Loader\ClassMapAutoloader' => array(
__DIR__ . '/autoload_classmap.php',
),
);
and here content of autoload_classmap.php
<?php
return array(
'FirePHP' => realpath(APPLICATION_PATH . '/vendor/FirePHP').'/FirePHP.php',
);
FirePHP.php(renamed from FirePHP.class.php) downloaded from official site.
then you can write below code in any place of your module and it will work
use Zend\Log\Writer\FirePhp;
use Zend\Log\Logger;
$writer = new FirePhp();
$logger = new Logger();
$logger->addWriter($writer);
$logger->info("hi");
Am I supposed to get this from somewhere else?
Yes, you need to get FirePHP into your project and autoloading.
If you're using composer (and I recommend that you do), just add:
"firephp/firephp-core" : "dev-master"
(or similar) in your composer.json and update. If you're not using composer, you should grab the firephp libs, and let your autoloader know about them.

how to install SmallFry MVC Framework under Xampp

How to install and use SmallFry framework.
I downloaded it from https://github.com/maniator/SmallFry
Extracted it under htdocs and placed all content in folder: smallfry (C:\xampp\htdocs\smallfry).
Set Doc root to define('DOCROOT', 'C:/xampp/htdocs'); in Autoloader.php.
Changed db info to following settings---
$CONFIG->set('DB_INFO', array(
'host' => 'localhost',
'login' => 'root',
'password' => '',
'database' => 'smallfry',
));
Still getting the following error --
let me know what else need to be change as i m very new to this framework.
Apparently, the framework is a bit out-dated, as assigning the return vlaue of new by reference is indeed deprecated. You should look for $x =& new Obj; calls and remove the &.
The Fatal error should be fixed after fixing the other issues. According to the documentation, that method should exist.
Fatal error occurs due to first two errors.
Because of Deprecated warnings Config class wasn't loaded correctly.

Categories